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/coms_362_java/src/id3TagStuff/id3Data/ID3_String.java b/coms_362_java/src/id3TagStuff/id3Data/ID3_String.java
index 757d7aa..8f53a3f 100644
--- a/coms_362_java/src/id3TagStuff/id3Data/ID3_String.java
+++ b/coms_362_java/src/id3TagStuff/id3Data/ID3_String.java
@@ -1,49 +1,49 @@
package id3TagStuff.id3Data;
import controller.Util;
public class ID3_String implements ID3v2_XFrameData {
private String data;
/**
* Creates an ID3_String out of some bytes
*
* @param dataP
*/
public ID3_String(int[] dataP) {
data = new String(Util.castIntArrToByteArr(dataP));
}
@Override
public String toString() {
String stripped = trimNullChars(data);
return stripped;
}
- private static String trimNullChars(String data2) {
+ public static String trimNullChars(String data2) {
String dat = data2;
if (!(Character.isDigit(dat.charAt(0)) || Character.isLetter(dat.charAt(0)))) {
dat = dat.substring(1);
}
if (!(Character.isDigit(dat.charAt(dat.length() - 1)) || Character.isLetter(dat
.charAt(dat.length() - 1)))) {
dat = dat.substring(0, dat.length() - 1);
}
return dat;
}
@Override
public String getType() {
return "String";
}
@Override
public int[] getByteRepresentation(int versionNumber) {
byte encoding = 0;
byte[] ret = new byte[1 + data.getBytes().length];
ret[0] = encoding;
System.arraycopy(data.getBytes(), 0, ret, 1, data.getBytes().length);
return Util.castByteArrToIntArr(ret);
}
}
| true | true | private static String trimNullChars(String data2) {
String dat = data2;
if (!(Character.isDigit(dat.charAt(0)) || Character.isLetter(dat.charAt(0)))) {
dat = dat.substring(1);
}
if (!(Character.isDigit(dat.charAt(dat.length() - 1)) || Character.isLetter(dat
.charAt(dat.length() - 1)))) {
dat = dat.substring(0, dat.length() - 1);
}
return dat;
}
| public static String trimNullChars(String data2) {
String dat = data2;
if (!(Character.isDigit(dat.charAt(0)) || Character.isLetter(dat.charAt(0)))) {
dat = dat.substring(1);
}
if (!(Character.isDigit(dat.charAt(dat.length() - 1)) || Character.isLetter(dat
.charAt(dat.length() - 1)))) {
dat = dat.substring(0, dat.length() - 1);
}
return dat;
}
|
diff --git a/game/things/Door.java b/game/things/Door.java
index 04339ed..7279969 100644
--- a/game/things/Door.java
+++ b/game/things/Door.java
@@ -1,142 +1,142 @@
package game.things;
import java.util.ArrayList;
import java.util.List;
import util.Direction;
import serialization.*;
import game.*;
public class Door extends AbstractGameThing implements Togglable {
public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof Door? "door" : null;
}
});
union.addSerializer("door", new Serializer<GameThing>(){
public Tree write(GameThing o){
Door in = (Door)o;
Tree out = new Tree();
out.add(new Tree.Entry("open", new Tree(in.openRenderer)));
out.add(new Tree.Entry("close", new Tree(in.closedRenderer)));
out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open)));
- out.add(new Tree.Entry("doorcode", new Tree(in.openRenderer)));
+ out.add(new Tree.Entry("doorcode", new Tree(in.doorcode)));
return out;
}
public GameThing read(Tree in) throws ParseException {
if(in.findNull("doorcode") == null){
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
"blank");
}
else{
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
in.findNull("doorcode").value());
}
}
});
}
private final String openRenderer;
private final String closedRenderer;
private String doorcode;
private boolean open;
public Door(GameWorld world, String closedRenderer, String openRenderer, boolean open, String drcd){
super(world);
this.openRenderer = openRenderer;
this.closedRenderer = closedRenderer;
this.open = open;
this.doorcode = drcd;
update();
}
@Override
public String renderer(){
return open?openRenderer:closedRenderer;
}
@Override
public List<String> interactions(){
return new ArrayList<String>(){private static final long serialVersionUID = 1L;{this.add(defaultInteraction());}};
}
@Override
public String defaultInteraction() {
if(open) {
return "close";
}
else {
return "open";
}
}
public void walkAndSetOpen(final boolean s, final Player p, final String say){
Location l = location();
final GameThing g = this;
if(l instanceof Level.Location)
p.moveTo((Level.Location)l, 1, new Runnable(){
public void run(){
open = s;
update();
world().emitSay(g, p, say);
}
});
p.face(l);
}
@Override
public void interact(String inter, Player who) {
if(inter.equals("close"))
walkAndSetOpen(false, who, "You close the door");
else if(inter.equals("open")){
if(!doorcode.equals("blank")){
for(GameThing gt : who.inventory().contents()){
if(gt instanceof game.things.Key && ((Key)gt).doorcode().equals(this.doorcode)){
walkAndSetOpen(true, who, "You unlock and open the door");
return;
}
}
walkAndSetOpen(false, who, "You can't open the "+doorcode+" door; it's locked");
}
else{
walkAndSetOpen(true, who, "You unlock the door");
}
}
else super.interact(inter, who);
}
@Override
public String name(){
return "Door";
}
@Override
public boolean canWalkInto(Direction d, Character who){
return open;
}
@Override
public int renderLevel() {
return ui.isometric.abstractions.IsoSquare.WALL;
}
public String doorcode(){
return doorcode;
}
public void setDoorcode(String drcd){
this.doorcode = drcd;
}
public void toggle(){
open ^= true;
update();
}
}
| true | true | public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof Door? "door" : null;
}
});
union.addSerializer("door", new Serializer<GameThing>(){
public Tree write(GameThing o){
Door in = (Door)o;
Tree out = new Tree();
out.add(new Tree.Entry("open", new Tree(in.openRenderer)));
out.add(new Tree.Entry("close", new Tree(in.closedRenderer)));
out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open)));
out.add(new Tree.Entry("doorcode", new Tree(in.openRenderer)));
return out;
}
public GameThing read(Tree in) throws ParseException {
if(in.findNull("doorcode") == null){
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
"blank");
}
else{
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
in.findNull("doorcode").value());
}
}
});
}
| public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){
union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){
public String type(GameThing g){
return g instanceof Door? "door" : null;
}
});
union.addSerializer("door", new Serializer<GameThing>(){
public Tree write(GameThing o){
Door in = (Door)o;
Tree out = new Tree();
out.add(new Tree.Entry("open", new Tree(in.openRenderer)));
out.add(new Tree.Entry("close", new Tree(in.closedRenderer)));
out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open)));
out.add(new Tree.Entry("doorcode", new Tree(in.doorcode)));
return out;
}
public GameThing read(Tree in) throws ParseException {
if(in.findNull("doorcode") == null){
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
"blank");
}
else{
return new Door(world, in.find("close").value(), in.find("open").value(),
Serializers.Serializer_Boolean.read(in.find("state")),
in.findNull("doorcode").value());
}
}
});
}
|
diff --git a/src/com/tools/tvguide/managers/DnsManager.java b/src/com/tools/tvguide/managers/DnsManager.java
index 354809c..cff055b 100644
--- a/src/com/tools/tvguide/managers/DnsManager.java
+++ b/src/com/tools/tvguide/managers/DnsManager.java
@@ -1,75 +1,77 @@
package com.tools.tvguide.managers;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.tools.tvguide.utils.NetDataGetter;
import com.tools.tvguide.utils.Utility;
import android.content.Context;
public class DnsManager
{
private Context mContext;
private String mIpAddress;
public DnsManager(Context context)
{
mContext = context;
}
public String getIPAddress(String hostName) throws UnknownHostException
{
InetAddress addr = null;
if (mIpAddress != null)
return mIpAddress;
String ipAddress = getIPFrom_chinaz(hostName);
if (ipAddress != null)
{
mIpAddress = ipAddress;
return ipAddress;
}
addr = InetAddress.getByName (hostName);
ipAddress = addr.getHostAddress();
mIpAddress = ipAddress;
return ipAddress;
}
private String getIPFrom_chinaz(final String hostName)
{
String ipAddress = null;
String url = UrlManager.URL_CHINAZ_IP + "?IP=" + hostName;
NetDataGetter getter;
try
{
getter = new NetDataGetter(url);
String html = getter.getStringData();
+ if (html == null)
+ return null;
Pattern resultPattern = Pattern.compile("查询结果\\[1\\](.+)</");
Matcher resultMatcher = resultPattern.matcher(html);
if (resultMatcher.find())
{
String result = resultMatcher.group();
Pattern ipPattern = Pattern.compile("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])");
Matcher ipMatcher = ipPattern.matcher(result);
if (ipMatcher.find())
{
ipAddress = ipMatcher.group();
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
if (!Utility.isIPAddress(ipAddress))
return null;
return ipAddress;
}
}
| true | true | private String getIPFrom_chinaz(final String hostName)
{
String ipAddress = null;
String url = UrlManager.URL_CHINAZ_IP + "?IP=" + hostName;
NetDataGetter getter;
try
{
getter = new NetDataGetter(url);
String html = getter.getStringData();
Pattern resultPattern = Pattern.compile("查询结果\\[1\\](.+)</");
Matcher resultMatcher = resultPattern.matcher(html);
if (resultMatcher.find())
{
String result = resultMatcher.group();
Pattern ipPattern = Pattern.compile("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])");
Matcher ipMatcher = ipPattern.matcher(result);
if (ipMatcher.find())
{
ipAddress = ipMatcher.group();
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
if (!Utility.isIPAddress(ipAddress))
return null;
return ipAddress;
}
| private String getIPFrom_chinaz(final String hostName)
{
String ipAddress = null;
String url = UrlManager.URL_CHINAZ_IP + "?IP=" + hostName;
NetDataGetter getter;
try
{
getter = new NetDataGetter(url);
String html = getter.getStringData();
if (html == null)
return null;
Pattern resultPattern = Pattern.compile("查询结果\\[1\\](.+)</");
Matcher resultMatcher = resultPattern.matcher(html);
if (resultMatcher.find())
{
String result = resultMatcher.group();
Pattern ipPattern = Pattern.compile("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])");
Matcher ipMatcher = ipPattern.matcher(result);
if (ipMatcher.find())
{
ipAddress = ipMatcher.group();
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
if (!Utility.isIPAddress(ipAddress))
return null;
return ipAddress;
}
|
diff --git a/fap/app/controllers/fap/LoggerController.java b/fap/app/controllers/fap/LoggerController.java
index 521a3a87..5e1d9597 100644
--- a/fap/app/controllers/fap/LoggerController.java
+++ b/fap/app/controllers/fap/LoggerController.java
@@ -1,276 +1,276 @@
package controllers.fap;
import play.*;
import play.mvc.*;
import properties.FapProperties;
import controllers.fap.*;
import tags.ReflectionUtils;
import validation.*;
import models.*;
import java.text.SimpleDateFormat;
import java.util.*;
import messages.Messages;
import messages.Messages.MessageType;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import org.apache.log4j.Appender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.config.PropertyGetter.PropertyCallback;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import emails.Mails;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
public class LoggerController extends GenericController {
private static Logger log = Logger.getLogger("Paginas");
public static void index(){
log.info("Visitando página: fap/Admin/logs.html");
renderTemplate("fap/Admin/logs.html");
}
public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
- nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
+ nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
@Util
@SuppressWarnings("deprecation")
private static boolean esHoy(Date date) {
Date hoy = new Date();
if ((hoy.getDate() == date.getDate()) && (hoy.getMonth() == date.getMonth()) && (hoy.getYear() == date.getYear()))
return true;
return false;
}
@Util
private static String nombreFichero(Date date, String loggerName) {
String fileName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
// busca entre los appenders dos que sean de tipo DailyRollingFile,
// preferentemente aquel cuyo nombre es "Daily" o "Auditable", que son los configurados inicialmente en
// los ficheros de configuracion
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
if (((DailyRollingFileAppender)appender).getName().equals(loggerName)){
break;
}
}
}
if (fileName == null){
return fileName;
}
if (!esHoy(date)) {
fileName += "."+(date.getYear()+1900)+"-";
if (date.getMonth() < 9)
fileName += "0";
fileName += (date.getMonth()+1)+"-";
if (date.getDate() < 10)
fileName += "0";
fileName += date.getDate();
}
return fileName;
}
@SuppressWarnings("deprecation")
public static Date diaSiguiente (Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
}
| true | true | public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
| public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
|
diff --git a/src/codegen/DebugCodeInserter.java b/src/codegen/DebugCodeInserter.java
index 230b4d0..2e9e0bc 100644
--- a/src/codegen/DebugCodeInserter.java
+++ b/src/codegen/DebugCodeInserter.java
@@ -1,331 +1,331 @@
/*
* Tracing debug code insertion utility.
* Copyright (C) 2013 Zuben El Acribi
*
* 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 codegen;
import java.util.ArrayList;
import codegen.Annotations.Type;
import bnf.Tree;
import bnf.ParseTree;
public class DebugCodeInserter {
private ParseTree parseTree;
private Annotations ann;
public DebugCodeInserter(ParseTree parseTree, Annotations ann) {
this.parseTree = parseTree;
this.ann = ann;
ann.newFile(parseTree.filename);
}
public DebugCodeInserter run() {
insertDebugCode(parseTree.tree);
return this;
}
void insertDebugCode(Tree tree) {
if (tree.def.parent.node.equals("MethodDeclaratorRest")) { // MethodDeclaratorRest: FormalParameters {'[' ']'} ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(3).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("VoidMethodDeclaratorRest")) { // VoidMethodDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(2).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("ConstructorDeclaratorRest")) { // ConstructorDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] Block
block(tree.branches.get(2), tree.branches.get(0));
} else if (tree.def.parent.node.equals("Expression")) {
ArrayList<String> assignmentVars = new ArrayList<String>();
if (traceableExpression(tree, assignmentVars)) {
tree.prefix = "$.$.$(" + ann.annotation(Type.expr, tree.begin, tree.end) + "l, ";
tree.suffix = ")";
}
if (!(tree.parent != null && tree.parent.parent != null && tree.parent.parent.def.node.equals("ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate]"))) {
if (assignmentVars.size() > 0) {
StringBuffer buff = new StringBuffer();
for (String s: assignmentVars) {
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append(");");
}
if (tree.parent != null && tree.parent.def.node.equals("StatementExpression ';'")) {
if (tree.parent.suffix != null) {
tree.parent.suffix += buff;
} else {
tree.parent.suffix = buff.toString();
}
}
}
}
} else if (tree.def.parent.node.equals("BlockStatement")) { // BlockStatement: LocalVariableDeclarationStatement | ClassOrInterfaceDeclaration | [Identifier ':'] Statement
if (tree.branches.get(0) != null) { // LocalVariableDeclarationStatement: { VariableModifier } Type VariableDeclarators ';'
tree = tree.branches.get(0);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
Tree t = tree.branches.get(2); // VariableDeclarators: VariableDeclarator { ',' VariableDeclarator }
StringBuffer buff = new StringBuffer();
String var = t.branches.get(0).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
t = t.branches.get(1);
for (Tree b: t.branches) {
var = b.branches.get(1).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, t.begin, t.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
}
tree.suffix = buff.toString();
- } else if (tree.branches.get(2) != null) { // [Identifier ':'] Statement
+ } else if (tree.branches.size() > 2 && tree.branches.get(2) != null) { // [Identifier ':'] Statement
tree = tree.branches.get(2);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
}
} else if (tree.def.node.startsWith("'if'") && tree.def.branches.size() > 0) { // 'if' ParExpression Statement ['else' Statement]
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
if (tree.branches.size() > 3 && tree.branches.get(3).node.length() > 0) {
t = tree.branches.get(3).branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
}
} else if (tree.def.node.startsWith("'for'") && tree.def.branches.size() > 0) { // 'for' '(' ForControl ')' Statement
ArrayList<String> declaredVars = new ArrayList<String>();
Tree t = tree.branches.get(2).branches.get(0); // {VariableModifier} Type VariableDeclaratorId ForVarControlRest
if (t != null) {
Tree u = t.branches.get(2).branches.get(0);
declaredVars.add(u.node);
u = t.branches.get(3); // ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate] | ':' Expression
if (u.branches.get(0) != null) {
u = u.branches.get(0).branches.get(0); // [ '=' VariableInitializer ] { ',' VariableDeclarator }
u = u.branches.get(1);
for (Tree b: u.branches) {
declaredVars.add(b.branches.get(1).branches.get(0).node);
}
}
}
scope(tree);
StringBuffer buff = new StringBuffer();
for (String s: declaredVars) {
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append("); ");
}
t = tree.branches.get(4);
t.prefix = "{ " + buff + " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
} else if (tree.def.node.startsWith("'do'") && tree.def.branches.size() > 0) { // 'do' Statement 'while' ParExpression ';'
Tree t = tree.branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.startsWith("'while'") && tree.def.branches.size() > 0) { // 'while' ParExpression Statement
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.equals("{Modifier}")) {
boolean visibility = false;
for (Tree b: tree.branches) {
if (b.node.equals("protected") || b.node.equals("private")) {
b.prefix = "public";
b.hide = true;
visibility = true;
break;
} else if (b.node.equals("public")) {
visibility = true;
break;
}
}
if (!visibility) {
tree.prefix = "public ";
if (tree.begin == tree.end) {
Tree t = tree.parent;
int i = 0;
for (; i < t.branches.size(); i++) {
if (t.branches.get(i) == tree) {
break;
}
}
tree.begin = t.branches.get(i + 1).begin;
}
}
}
for (Tree b: tree.branches) {
if (b != null) {
insertDebugCode(b);
}
}
}
void block(Tree t, Tree params) {
t.prefix = formalParameters(params);
t.suffix = " finally { $.$.endscope(" + ann.annotation(Type.endscope, t.begin, t.end) + "l); } }";
}
String formalParameters(Tree t) {
String[] params = getListOfFormalParameters(t);
StringBuffer buff = new StringBuffer();
buff.append("{ $.$.scope(" + ann.annotation(Type.scope, t.begin, t.end) + "l); ");
for (int i = 0; i < params.length; i++) {
buff.append("$.$.var(" + ann.annotation(Type.vardecl, t.begin, t.end) + "l, \"");
buff.append(params[i]);
buff.append("\", ");
buff.append(params[i]);
buff.append("); ");
}
buff.append("$.$.step(" + ann.annotation(Type.step, t.begin, t.end) + "l); try ");
return buff.toString();
}
String[] getListOfFormalParameters(Tree t) { // FormalParameters: '(' [FormalParameterDecls] ')'
ArrayList<String> l = new ArrayList<String>();
if (t.branches.get(1).node.length() > 0) {
while (true) {
t = t.branches.get(1); // FormalParameterDecls: {VariableModifier} Type FormalParameterDeclsRest
t = t.branches.get(2); // FormalParameterDeclsRest: VariableDeclaratorId [ ',' FormalParameterDecls ] | '...' VariableDeclaratorId
if (t.branches.get(0) != null) {
t = t.branches.get(0);
l.add(t.branches.get(0).node);
if (t.branches.get(1).node.length() > 0) {
t = t.branches.get(1);
} else {
break;
}
} else {
t = t.branches.get(1);
l.add(t.branches.get(1).node);
break;
}
}
}
return l.toArray(new String[0]);
}
boolean traceableExpression(Tree t, ArrayList<String> assignmentVars) { // Expression: Expression1 [ AssignmentOperator Expression ]
Tree original = t;
if (t.branches.get(1).node.length() > 0) {
String name = t.branches.get(0).node;
boolean isIdentitifer = true;
for (int i = 0; i < name.length(); i++) {
if (!Character.isLetterOrDigit(name.charAt(i))) {
isIdentitifer = false;
break;
}
}
if (isIdentitifer) {
assignmentVars.add(name);
}
t = t.branches.get(1).branches.get(1);
traceableExpression(t, assignmentVars);
return false;
} else {
t = t.branches.get(0); // Expression1: Expression2 [ Expression1Rest ]
if (t.branches.get(1).node.length() == 0) { // Expression1Rest: '?' Expression ':' Expression1
// Tree u = t.branches.get(0);
// u.prefix = "$.$.$(";
// u.suffix = ")";
// traceableExpression(t.branches.get(0), assignmentVars);
// traceableExpression(t.branches.get(1).branches.get(1), assignmentVars);
// traceableExpression(t.branches.get(1).branches.get(3), assignmentVars);
// } else {
t = t.branches.get(0); // Expression2: Expression3 [ Expression2Rest ]
if (t.branches.get(1).node.length() == 0) {
t = t.branches.get(0); // Expression3: PrefixOp Expression3 | '(' ( Type | Expression ) ')' Expression3 | Primary { Selector } { PostfixOp })
if (t.branches.size() > 2 && t.branches.get(2) != null) {
t = t.branches.get(2);
Tree u = t.branches.get(0).branches.get(0);
if (u != null) {
return false; // Literal
}
u = t.branches.get(0);
if (u.branches.size() > 7) {
u = u.branches.get(7);
if (u != null) { // Identifier { '.' Identifier } [IdentifierSuffix]
if (u.branches.size() > 2 && u.branches.get(2).node.length() > 0) {
return !original.parent.def.node.equals("StatementExpression ';'");
}
}
}
}
}
}
}
return true;
}
void scope(Tree t) {
while (t.parent != null && t.parent.parent != null && t.parent.parent.def.node.equals("Identifier ':' Statement")) {
t = t.parent.parent; // Statement: Block | ';' | Identifier ':' Statement | ...
}
if (t.parent != null && t.parent.parent != null && t.parent.parent.def.node.equals("[Identifier ':'] Statement") && t.parent.parent.branches.get(0).node.length() > 0) {
t = t.parent.parent; // [Identifier ':'] Statement
}
if (t.prefix == null) {
t.prefix = "";
}
t.prefix += "$.$.scope(" + ann.annotation(Type.scope, t.begin, t.end) + "l); try { ";
if (t.suffix == null) {
t.suffix = "";
}
t.suffix += " } finally { $.$.endscope(" + ann.annotation(Type.endscope, t.begin, t.end) + "l); } ";
}
public ParseTree getParseTree() {
return parseTree;
}
}
| true | true | void insertDebugCode(Tree tree) {
if (tree.def.parent.node.equals("MethodDeclaratorRest")) { // MethodDeclaratorRest: FormalParameters {'[' ']'} ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(3).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("VoidMethodDeclaratorRest")) { // VoidMethodDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(2).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("ConstructorDeclaratorRest")) { // ConstructorDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] Block
block(tree.branches.get(2), tree.branches.get(0));
} else if (tree.def.parent.node.equals("Expression")) {
ArrayList<String> assignmentVars = new ArrayList<String>();
if (traceableExpression(tree, assignmentVars)) {
tree.prefix = "$.$.$(" + ann.annotation(Type.expr, tree.begin, tree.end) + "l, ";
tree.suffix = ")";
}
if (!(tree.parent != null && tree.parent.parent != null && tree.parent.parent.def.node.equals("ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate]"))) {
if (assignmentVars.size() > 0) {
StringBuffer buff = new StringBuffer();
for (String s: assignmentVars) {
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append(");");
}
if (tree.parent != null && tree.parent.def.node.equals("StatementExpression ';'")) {
if (tree.parent.suffix != null) {
tree.parent.suffix += buff;
} else {
tree.parent.suffix = buff.toString();
}
}
}
}
} else if (tree.def.parent.node.equals("BlockStatement")) { // BlockStatement: LocalVariableDeclarationStatement | ClassOrInterfaceDeclaration | [Identifier ':'] Statement
if (tree.branches.get(0) != null) { // LocalVariableDeclarationStatement: { VariableModifier } Type VariableDeclarators ';'
tree = tree.branches.get(0);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
Tree t = tree.branches.get(2); // VariableDeclarators: VariableDeclarator { ',' VariableDeclarator }
StringBuffer buff = new StringBuffer();
String var = t.branches.get(0).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
t = t.branches.get(1);
for (Tree b: t.branches) {
var = b.branches.get(1).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, t.begin, t.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
}
tree.suffix = buff.toString();
} else if (tree.branches.get(2) != null) { // [Identifier ':'] Statement
tree = tree.branches.get(2);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
}
} else if (tree.def.node.startsWith("'if'") && tree.def.branches.size() > 0) { // 'if' ParExpression Statement ['else' Statement]
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
if (tree.branches.size() > 3 && tree.branches.get(3).node.length() > 0) {
t = tree.branches.get(3).branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
}
} else if (tree.def.node.startsWith("'for'") && tree.def.branches.size() > 0) { // 'for' '(' ForControl ')' Statement
ArrayList<String> declaredVars = new ArrayList<String>();
Tree t = tree.branches.get(2).branches.get(0); // {VariableModifier} Type VariableDeclaratorId ForVarControlRest
if (t != null) {
Tree u = t.branches.get(2).branches.get(0);
declaredVars.add(u.node);
u = t.branches.get(3); // ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate] | ':' Expression
if (u.branches.get(0) != null) {
u = u.branches.get(0).branches.get(0); // [ '=' VariableInitializer ] { ',' VariableDeclarator }
u = u.branches.get(1);
for (Tree b: u.branches) {
declaredVars.add(b.branches.get(1).branches.get(0).node);
}
}
}
scope(tree);
StringBuffer buff = new StringBuffer();
for (String s: declaredVars) {
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append("); ");
}
t = tree.branches.get(4);
t.prefix = "{ " + buff + " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
} else if (tree.def.node.startsWith("'do'") && tree.def.branches.size() > 0) { // 'do' Statement 'while' ParExpression ';'
Tree t = tree.branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.startsWith("'while'") && tree.def.branches.size() > 0) { // 'while' ParExpression Statement
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.equals("{Modifier}")) {
boolean visibility = false;
for (Tree b: tree.branches) {
if (b.node.equals("protected") || b.node.equals("private")) {
b.prefix = "public";
b.hide = true;
visibility = true;
break;
} else if (b.node.equals("public")) {
visibility = true;
break;
}
}
if (!visibility) {
tree.prefix = "public ";
if (tree.begin == tree.end) {
Tree t = tree.parent;
int i = 0;
for (; i < t.branches.size(); i++) {
if (t.branches.get(i) == tree) {
break;
}
}
tree.begin = t.branches.get(i + 1).begin;
}
}
}
for (Tree b: tree.branches) {
if (b != null) {
insertDebugCode(b);
}
}
}
| void insertDebugCode(Tree tree) {
if (tree.def.parent.node.equals("MethodDeclaratorRest")) { // MethodDeclaratorRest: FormalParameters {'[' ']'} ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(3).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("VoidMethodDeclaratorRest")) { // VoidMethodDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] (Block | ';')
Tree params = tree.branches.get(0);
tree = tree.branches.get(2).branches.get(0);
if (tree == null) {
return;
}
block(tree, params);
} else if (tree.def.parent.node.equals("ConstructorDeclaratorRest")) { // ConstructorDeclaratorRest: FormalParameters ['throws' QualifiedIdentifierList] Block
block(tree.branches.get(2), tree.branches.get(0));
} else if (tree.def.parent.node.equals("Expression")) {
ArrayList<String> assignmentVars = new ArrayList<String>();
if (traceableExpression(tree, assignmentVars)) {
tree.prefix = "$.$.$(" + ann.annotation(Type.expr, tree.begin, tree.end) + "l, ";
tree.suffix = ")";
}
if (!(tree.parent != null && tree.parent.parent != null && tree.parent.parent.def.node.equals("ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate]"))) {
if (assignmentVars.size() > 0) {
StringBuffer buff = new StringBuffer();
for (String s: assignmentVars) {
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append(");");
}
if (tree.parent != null && tree.parent.def.node.equals("StatementExpression ';'")) {
if (tree.parent.suffix != null) {
tree.parent.suffix += buff;
} else {
tree.parent.suffix = buff.toString();
}
}
}
}
} else if (tree.def.parent.node.equals("BlockStatement")) { // BlockStatement: LocalVariableDeclarationStatement | ClassOrInterfaceDeclaration | [Identifier ':'] Statement
if (tree.branches.get(0) != null) { // LocalVariableDeclarationStatement: { VariableModifier } Type VariableDeclarators ';'
tree = tree.branches.get(0);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
Tree t = tree.branches.get(2); // VariableDeclarators: VariableDeclarator { ',' VariableDeclarator }
StringBuffer buff = new StringBuffer();
String var = t.branches.get(0).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.var, tree.begin, tree.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
t = t.branches.get(1);
for (Tree b: t.branches) {
var = b.branches.get(1).branches.get(0).node;
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, t.begin, t.end) + "l, \"");
buff.append(var);
buff.append("\", ");
buff.append(var);
buff.append(");");
}
tree.suffix = buff.toString();
} else if (tree.branches.size() > 2 && tree.branches.get(2) != null) { // [Identifier ':'] Statement
tree = tree.branches.get(2);
tree.prefix = " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
}
} else if (tree.def.node.startsWith("'if'") && tree.def.branches.size() > 0) { // 'if' ParExpression Statement ['else' Statement]
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
if (tree.branches.size() > 3 && tree.branches.get(3).node.length() > 0) {
t = tree.branches.get(3).branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " }";
}
} else if (tree.def.node.startsWith("'for'") && tree.def.branches.size() > 0) { // 'for' '(' ForControl ')' Statement
ArrayList<String> declaredVars = new ArrayList<String>();
Tree t = tree.branches.get(2).branches.get(0); // {VariableModifier} Type VariableDeclaratorId ForVarControlRest
if (t != null) {
Tree u = t.branches.get(2).branches.get(0);
declaredVars.add(u.node);
u = t.branches.get(3); // ForVariableDeclaratorsRest ';' [Expression] ';' [ForUpdate] | ':' Expression
if (u.branches.get(0) != null) {
u = u.branches.get(0).branches.get(0); // [ '=' VariableInitializer ] { ',' VariableDeclarator }
u = u.branches.get(1);
for (Tree b: u.branches) {
declaredVars.add(b.branches.get(1).branches.get(0).node);
}
}
}
scope(tree);
StringBuffer buff = new StringBuffer();
for (String s: declaredVars) {
buff.append(" $.$.var(" + ann.annotation(Type.vardecl, tree.begin, tree.end) + "l, \"");
buff.append(s);
buff.append("\", ");
buff.append(s);
buff.append("); ");
}
t = tree.branches.get(4);
t.prefix = "{ " + buff + " $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
} else if (tree.def.node.startsWith("'do'") && tree.def.branches.size() > 0) { // 'do' Statement 'while' ParExpression ';'
Tree t = tree.branches.get(1);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.startsWith("'while'") && tree.def.branches.size() > 0) { // 'while' ParExpression Statement
Tree t = tree.branches.get(2);
t.prefix = "{ $.$.step(" + ann.annotation(Type.step, tree.begin, tree.end) + "l);";
t.suffix = " } ";
scope(tree);
} else if (tree.def.node.equals("{Modifier}")) {
boolean visibility = false;
for (Tree b: tree.branches) {
if (b.node.equals("protected") || b.node.equals("private")) {
b.prefix = "public";
b.hide = true;
visibility = true;
break;
} else if (b.node.equals("public")) {
visibility = true;
break;
}
}
if (!visibility) {
tree.prefix = "public ";
if (tree.begin == tree.end) {
Tree t = tree.parent;
int i = 0;
for (; i < t.branches.size(); i++) {
if (t.branches.get(i) == tree) {
break;
}
}
tree.begin = t.branches.get(i + 1).begin;
}
}
}
for (Tree b: tree.branches) {
if (b != null) {
insertDebugCode(b);
}
}
}
|
diff --git a/src/com/winthier/simpleshop/sql/ListTransactionsRequest.java b/src/com/winthier/simpleshop/sql/ListTransactionsRequest.java
index 701d7a7..7bb42af 100644
--- a/src/com/winthier/simpleshop/sql/ListTransactionsRequest.java
+++ b/src/com/winthier/simpleshop/sql/ListTransactionsRequest.java
@@ -1,153 +1,155 @@
package com.winthier.simpleshop.sql;
import com.winthier.libsql.SQLRequest;
import com.winthier.simpleshop.SimpleShopPlugin;
import com.winthier.simpleshop.Util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.milkbowl.vault.item.ItemInfo;
import net.milkbowl.vault.item.Items;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
public class ListTransactionsRequest extends BukkitRunnable implements SQLRequest {
private final SimpleShopPlugin plugin;
private final CommandSender sender;
private final String owner;
private final int page;
public static final int PAGE_SIZE = 10;
// Result
private ResultSet result = null;
private int count;
private static Map<Integer, String> enchantmentNameMap = new HashMap<Integer, String>();
private static void addMapping(Enchantment enchantment, String name) {
enchantmentNameMap.put(enchantment.getId(), name);
}
public static String getEnchantmentName(Enchantment enchantment) {
String result = enchantmentNameMap.get(enchantment.getId());
if (result == null) result = enchantment.getName();
return result;
}
static {
addMapping(Enchantment.ARROW_DAMAGE, "Power");
addMapping(Enchantment.ARROW_FIRE, "Flame");
addMapping(Enchantment.ARROW_INFINITE, "Infinity");
addMapping(Enchantment.ARROW_KNOCKBACK, "Knockback");
addMapping(Enchantment.DAMAGE_ALL, "Sharpness");
addMapping(Enchantment.DAMAGE_ARTHROPODS, "Bane of Arthropods");
addMapping(Enchantment.DAMAGE_UNDEAD, "Smite");
addMapping(Enchantment.DIG_SPEED, "Efficiency");
addMapping(Enchantment.DURABILITY, "Unbreaking");
addMapping(Enchantment.FIRE_ASPECT, "Fire Aspect");
addMapping(Enchantment.KNOCKBACK, "Knockback");
addMapping(Enchantment.LOOT_BONUS_BLOCKS, "Fortune");
addMapping(Enchantment.LOOT_BONUS_MOBS, "Looting");
addMapping(Enchantment.OXYGEN, "Respiration");
addMapping(Enchantment.PROTECTION_ENVIRONMENTAL, "Protection");
addMapping(Enchantment.PROTECTION_EXPLOSIONS, "Blast Protection");
addMapping(Enchantment.PROTECTION_FALL, "Feather Falling");
addMapping(Enchantment.PROTECTION_FIRE, "Fire Protection");
addMapping(Enchantment.PROTECTION_PROJECTILE, "Projectile Protection");
addMapping(Enchantment.SILK_TOUCH, "Silk Touch");
addMapping(Enchantment.THORNS, "Thorns");
addMapping(Enchantment.WATER_WORKER, "Water Affinity");
}
public ListTransactionsRequest(SimpleShopPlugin plugin, CommandSender sender, String owner, int page) {
this.plugin = plugin;
this.sender = sender;
this.owner = owner;
this.page = page;
}
@Override
public void execute(Connection c) throws SQLException {
PreparedStatement s;
ResultSet result;
s = c.prepareStatement("SELECT COUNT(*) from simpleshop_transactions WHERE owner = ?");
s.setString(1, owner);
result = s.executeQuery();
if (result.next()) {
this.count = result.getInt(1);
}
s.close();
s = c.prepareStatement(
"SELECT * from `simpleshop_transactions`" +
" WHERE `owner` = ?" +
" ORDER BY `id` DESC" +
" LIMIT ?,?");
int i = 1;
s.setString(i++, owner);
s.setInt(i++, page * PAGE_SIZE);
s.setInt(i++, PAGE_SIZE);
this.result = s.executeQuery();
runTask(plugin);
}
@Override
public void run() {
try {
result(result);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void result(ResultSet result) throws SQLException {
Util.sendMessage(sender, "&bTransaction log for %s (page %d/%d)", owner, page + 1, (count - 1) / PAGE_SIZE + 1);
while (result.next()) {
String name;
final String matName = result.getString("material");
final Material mat = Material.matchMaterial(matName);
if (mat == null) {
System.err.println("[SimpleShop] invalid material in database: " + matName);
continue;
}
ItemInfo info = Items.itemByType(mat, (short)result.getInt("itemdata"));
if (info == null) {
name = "" + matName + ":" + result.getInt("itemdata");
} else {
name = info.getName();
}
String displayName = result.getString("display_name");
if (displayName != null) name += " Name=\"" + ChatColor.stripColor(displayName) + "\"";
StringBuilder sb = new StringBuilder();
for (Enchantment enchantment : Enchantment.values()) {
- int level = result.getInt("enchantment_" + enchantment.getName().toLowerCase());
+ String enchantmentName = "enchantment_" + enchantment.getName().toLowerCase();
+ if (enchantmentName.contains("unknown")) continue;
+ int level = result.getInt(enchantmentName);
if (level > 0) {
if (sb.length() > 0) sb.append(", ");
sb.append(getEnchantmentName(enchantment));
sb.append(" ").append(level);
}
}
if (sb.length() > 0) name += " " + sb.toString();
String player = result.getString("player");
String shopType = result.getString("shop_type");
Date date = result.getTimestamp("time");
Calendar cal = Calendar.getInstance();
int amount = result.getInt("amount");
double price = result.getDouble("price");
cal.setTime(date);
String[] months = DateFormatSymbols.getInstance().getShortMonths();
Util.sendMessage(sender, "[&b%s %02d&r] &b%s &3%s &b%d&3x&b%s&3 for &b%s", months[cal.get(Calendar.MONTH)], cal.get(Calendar.DAY_OF_MONTH), player, (shopType.equals("buy") ? "bought" : "sold"), amount, name, SimpleShopPlugin.formatPrice(price));
}
}
}
| true | true | public void result(ResultSet result) throws SQLException {
Util.sendMessage(sender, "&bTransaction log for %s (page %d/%d)", owner, page + 1, (count - 1) / PAGE_SIZE + 1);
while (result.next()) {
String name;
final String matName = result.getString("material");
final Material mat = Material.matchMaterial(matName);
if (mat == null) {
System.err.println("[SimpleShop] invalid material in database: " + matName);
continue;
}
ItemInfo info = Items.itemByType(mat, (short)result.getInt("itemdata"));
if (info == null) {
name = "" + matName + ":" + result.getInt("itemdata");
} else {
name = info.getName();
}
String displayName = result.getString("display_name");
if (displayName != null) name += " Name=\"" + ChatColor.stripColor(displayName) + "\"";
StringBuilder sb = new StringBuilder();
for (Enchantment enchantment : Enchantment.values()) {
int level = result.getInt("enchantment_" + enchantment.getName().toLowerCase());
if (level > 0) {
if (sb.length() > 0) sb.append(", ");
sb.append(getEnchantmentName(enchantment));
sb.append(" ").append(level);
}
}
if (sb.length() > 0) name += " " + sb.toString();
String player = result.getString("player");
String shopType = result.getString("shop_type");
Date date = result.getTimestamp("time");
Calendar cal = Calendar.getInstance();
int amount = result.getInt("amount");
double price = result.getDouble("price");
cal.setTime(date);
String[] months = DateFormatSymbols.getInstance().getShortMonths();
Util.sendMessage(sender, "[&b%s %02d&r] &b%s &3%s &b%d&3x&b%s&3 for &b%s", months[cal.get(Calendar.MONTH)], cal.get(Calendar.DAY_OF_MONTH), player, (shopType.equals("buy") ? "bought" : "sold"), amount, name, SimpleShopPlugin.formatPrice(price));
}
}
| public void result(ResultSet result) throws SQLException {
Util.sendMessage(sender, "&bTransaction log for %s (page %d/%d)", owner, page + 1, (count - 1) / PAGE_SIZE + 1);
while (result.next()) {
String name;
final String matName = result.getString("material");
final Material mat = Material.matchMaterial(matName);
if (mat == null) {
System.err.println("[SimpleShop] invalid material in database: " + matName);
continue;
}
ItemInfo info = Items.itemByType(mat, (short)result.getInt("itemdata"));
if (info == null) {
name = "" + matName + ":" + result.getInt("itemdata");
} else {
name = info.getName();
}
String displayName = result.getString("display_name");
if (displayName != null) name += " Name=\"" + ChatColor.stripColor(displayName) + "\"";
StringBuilder sb = new StringBuilder();
for (Enchantment enchantment : Enchantment.values()) {
String enchantmentName = "enchantment_" + enchantment.getName().toLowerCase();
if (enchantmentName.contains("unknown")) continue;
int level = result.getInt(enchantmentName);
if (level > 0) {
if (sb.length() > 0) sb.append(", ");
sb.append(getEnchantmentName(enchantment));
sb.append(" ").append(level);
}
}
if (sb.length() > 0) name += " " + sb.toString();
String player = result.getString("player");
String shopType = result.getString("shop_type");
Date date = result.getTimestamp("time");
Calendar cal = Calendar.getInstance();
int amount = result.getInt("amount");
double price = result.getDouble("price");
cal.setTime(date);
String[] months = DateFormatSymbols.getInstance().getShortMonths();
Util.sendMessage(sender, "[&b%s %02d&r] &b%s &3%s &b%d&3x&b%s&3 for &b%s", months[cal.get(Calendar.MONTH)], cal.get(Calendar.DAY_OF_MONTH), player, (shopType.equals("buy") ? "bought" : "sold"), amount, name, SimpleShopPlugin.formatPrice(price));
}
}
|
diff --git a/crypto/src/org/bouncycastle/jce/provider/EC5Util.java b/crypto/src/org/bouncycastle/jce/provider/EC5Util.java
index 9fbc0218..0a940e50 100644
--- a/crypto/src/org/bouncycastle/jce/provider/EC5Util.java
+++ b/crypto/src/org/bouncycastle/jce/provider/EC5Util.java
@@ -1,54 +1,54 @@
package org.bouncycastle.jce.provider;
import java.security.spec.ECFieldF2m;
import java.security.spec.ECFieldFp;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.EllipticCurve;
import org.bouncycastle.math.ec.ECCurve;
public class EC5Util
{
static EllipticCurve convertCurve(
ECCurve curve,
byte[] seed)
{
if (curve instanceof ECCurve.Fp)
{
return new EllipticCurve(new ECFieldFp(((ECCurve.Fp)curve).getQ()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
ECCurve.F2m curveF2m = (ECCurve.F2m)curve;
int ks[];
if (curveF2m.isTrinomial())
{
ks = new int[] { curveF2m.getK1() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
- ks = new int[] { curveF2m.getK1(), curveF2m.getK2(), curveF2m.getK3() };
+ ks = new int[] { curveF2m.getK3(), curveF2m.getK2(), curveF2m.getK1() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
}
}
static ECParameterSpec convertSpec(
EllipticCurve ellipticCurve,
org.bouncycastle.jce.spec.ECParameterSpec spec)
{
return new ECParameterSpec(
ellipticCurve,
new ECPoint(
spec.getG().getX().toBigInteger(),
spec.getG().getY().toBigInteger()),
spec.getN(),
spec.getH().intValue());
}
}
| true | true | static EllipticCurve convertCurve(
ECCurve curve,
byte[] seed)
{
if (curve instanceof ECCurve.Fp)
{
return new EllipticCurve(new ECFieldFp(((ECCurve.Fp)curve).getQ()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
ECCurve.F2m curveF2m = (ECCurve.F2m)curve;
int ks[];
if (curveF2m.isTrinomial())
{
ks = new int[] { curveF2m.getK1() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
ks = new int[] { curveF2m.getK1(), curveF2m.getK2(), curveF2m.getK3() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
}
}
| static EllipticCurve convertCurve(
ECCurve curve,
byte[] seed)
{
if (curve instanceof ECCurve.Fp)
{
return new EllipticCurve(new ECFieldFp(((ECCurve.Fp)curve).getQ()), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
ECCurve.F2m curveF2m = (ECCurve.F2m)curve;
int ks[];
if (curveF2m.isTrinomial())
{
ks = new int[] { curveF2m.getK1() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
else
{
ks = new int[] { curveF2m.getK3(), curveF2m.getK2(), curveF2m.getK1() };
return new EllipticCurve(new ECFieldF2m(curveF2m.getM(), ks), curve.getA().toBigInteger(), curve.getB().toBigInteger(), seed);
}
}
}
|
diff --git a/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java b/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java
index a89f3aa6b..672b80e2e 100644
--- a/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java
+++ b/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java
@@ -1,660 +1,660 @@
/*
* This file is part of MyPet
*
* Copyright (C) 2011-2013 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet 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.
*
* MyPet 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.Keyle.MyPet.gui.skilltreecreator;
import de.Keyle.MyPet.gui.GuiMain;
import de.Keyle.MyPet.skill.*;
import de.Keyle.MyPet.skill.skills.info.ISkillInfo;
import de.Keyle.MyPet.util.MyPetVersion;
import de.Keyle.MyPet.util.Util;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class LevelCreator
{
JTree skillTreeTree;
JLabel skillTreeNameLabel;
JButton deleteLevelSkillButton;
JButton addLevelButton;
JButton addSkillButton;
JComboBox inheritanceComboBox;
JCheckBox inheritanceCheckBox;
JPanel levelCreatorPanel;
JButton backButton;
JButton copyButton;
JTextField permissionDisplayTextField;
JCheckBox displayNameCheckbox;
JCheckBox permissionCheckbox;
JTextField displayNameTextField;
JTextField permissionTextField;
JCheckBox levelUpMessageCheckBox;
JTextField levelUpMessageInput;
JFrame levelCreatorFrame;
DefaultTreeModel skillTreeTreeModel;
DefaultComboBoxModel inheritanceComboBoxModel;
SkillTree skillTree;
SkillTreeLevel selectedLevel = null;
SkillTreeMobType skillTreeMobType;
private static String[] skillNames = null;
int highestLevel = 0;
public LevelCreator()
{
if (skillNames == null)
{
skillNames = new String[SkillsInfo.getRegisteredSkillsInfo().size()];
int skillCounter = 0;
for (Class<? extends SkillTreeSkill> clazz : SkillsInfo.getRegisteredSkillsInfo())
{
SkillName sn = clazz.getAnnotation(SkillName.class);
if (sn != null)
{
skillNames[skillCounter++] = sn.value();
}
}
}
addLevelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = (String) JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE, null, null, "" + (highestLevel + 1));
if (response != null)
{
if (Util.isInt(response))
{
int newLevel = Integer.parseInt(response);
for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++)
{
if (Util.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()))
{
int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString());
if (newLevel == level)
{
JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
else if (newLevel < 1)
{
JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
highestLevel = Math.max(highestLevel, newLevel);
DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel);
skillTree.addLevel(newLevel);
((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode);
skillTreeTree.setSelectionPath(new TreePath(new Object[]{skillTreeTreeModel.getRoot(), levelNode}));
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
else
{
JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE);
}
}
}
});
addSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int level;
if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
}
else
{
return;
}
}
else
{
return;
}
String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, "");
if (choosenSkill != null)
{
ISkillInfo skill = SkillsInfo.getNewSkillInfoInstance(choosenSkill);
skillTree.addSkillToLevel(level, skill);
SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill);
skill.setDefaultProperties();
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode);
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
}
});
deleteLevelSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skillTreeTree.getSelectionPath().getPath().length == 2)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
skillTree.removeLevel(level);
}
else
{
return;
}
}
else if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2)));
skillTree.getLevel(level).removeSkill(index);
}
else
{
return;
}
}
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent();
skillTreeTree.updateUI();
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
}
});
skillTreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (e.getPath().getPath().length == 1)
{
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
else if (e.getPath().getPath().length == 2)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
if (level > 1 && skillTree.hasLevel(level))
{
levelUpMessageCheckBox.setEnabled(true);
selectedLevel = skillTree.getLevel(level);
if (selectedLevel.hasLevelupMessage())
{
levelUpMessageCheckBox.setSelected(true);
levelUpMessageInput.setEnabled(true);
levelUpMessageInput.setText(selectedLevel.getLevelupMessage());
}
else
{
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
}
}
}
}
else if (e.getPath().getPath().length == 3)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
}
});
inheritanceCheckBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (inheritanceCheckBox.isSelected())
{
inheritanceComboBox.setEnabled(true);
skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString());
}
else
{
inheritanceComboBox.setEnabled(false);
skillTree.setInheritance(null);
}
}
});
permissionCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (permissionCheckbox.isSelected())
{
permissionTextField.setEnabled(true);
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
}
else
{
permissionTextField.setEnabled(false);
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
});
displayNameCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (displayNameCheckbox.isSelected())
{
displayNameTextField.setEnabled(true);
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
else
{
displayNameTextField.setEnabled(false);
skillTree.setDisplayName(null);
}
}
});
backButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GuiMain.skilltreeCreator.getFrame().setEnabled(true);
levelCreatorFrame.setVisible(false);
}
});
inheritanceComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected())
{
if (!skillTree.getInheritance().equals(e.getItem().toString()))
{
skillTree.setInheritance(e.getItem().toString());
}
}
}
});
copyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
});
skillTreeTree.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode)
{
ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill();
if (skill.getClass().getAnnotation(SkillProperties.class) == null)
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (SkillsInfo.isValidSkill(skill.getName()))
{
if (skill.getGuiPanel() != null)
{
GuiMain.skillPropertyEditor.setSkill(skill);
}
else
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
GuiMain.skillPropertyEditor.getFrame().setVisible(true);
getFrame().setEnabled(false);
GuiMain.skillPropertyEditor.getFrame().setSize(GuiMain.skillPropertyEditor.getFrame().getWidth(), skill.getGuiPanel().getMainPanel().getHeight() + 90);
}
}
}
}
});
permissionTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", ""));
if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText()))
{
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
displayNameTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText()))
{
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageInput.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
- if (levelUpMessageCheckBox.isSelected() && selectedLevel != null && !selectedLevel.getLevelupMessage().equals(levelUpMessageInput.getText()))
+ if (levelUpMessageCheckBox.isSelected() && selectedLevel != null && (selectedLevel.getLevelupMessage() == null || !selectedLevel.getLevelupMessage().equals(levelUpMessageInput.getText())))
{
if (!levelUpMessageInput.getText().equalsIgnoreCase(""))
{
selectedLevel.setLevelupMessage(levelUpMessageInput.getText());
}
else
{
selectedLevel.setLevelupMessage(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageCheckBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
levelUpMessageInput.setEnabled(levelUpMessageCheckBox.isSelected());
}
});
}
public JPanel getMainPanel()
{
return levelCreatorPanel;
}
public JFrame getFrame()
{
if (levelCreatorFrame == null)
{
levelCreatorFrame = new JFrame("LevelCreator - MyPet " + MyPetVersion.getMyPetVersion());
}
return levelCreatorFrame;
}
public void setSkillTree(SkillTree skillTree, SkillTreeMobType skillTreeMobType)
{
this.skillTree = skillTree;
this.skillTreeMobType = skillTreeMobType;
highestLevel = 0;
if (skillTree.hasDisplayName())
{
displayNameTextField.setEnabled(true);
displayNameCheckbox.setSelected(true);
}
else
{
displayNameTextField.setEnabled(false);
displayNameCheckbox.setSelected(false);
}
displayNameTextField.setText(skillTree.getDisplayName());
if (skillTree.hasCustomPermissions())
{
permissionTextField.setEnabled(true);
permissionCheckbox.setSelected(true);
}
else
{
permissionTextField.setEnabled(false);
permissionCheckbox.setSelected(false);
}
permissionTextField.setText(skillTree.getPermission());
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
this.inheritanceComboBoxModel.removeAllElements();
inheritanceCheckBox.setSelected(false);
inheritanceCheckBox.setEnabled(false);
if (skillTreeMobType.getSkillTreeNames().size() > 1 || (!skillTreeMobType.getMobTypeName().equals("default") && SkillTreeMobType.getMobTypeByName("default").getSkillTreeNames().size() > 0))
{
inheritanceCheckBox.setEnabled(true);
ArrayList<String> skilltreeNames = new ArrayList<String>();
for (String skillTreeName : skillTreeMobType.getSkillTreeNames())
{
if (!skillTreeName.equals(skillTree.getName()) && !skilltreeNames.contains(skillTreeName))
{
skilltreeNames.add(skillTreeName);
inheritanceComboBoxModel.addElement(skillTreeName);
}
}
for (String skillTreeName : SkillTreeMobType.getMobTypeByName("default").getSkillTreeNames())
{
if (!skillTreeName.equals(skillTree.getName()) && !skilltreeNames.contains(skillTreeName))
{
skilltreeNames.add(skillTreeName);
inheritanceComboBoxModel.addElement(skillTreeName);
}
}
if (skillTree.getInheritance() != null && skillTreeMobType.getSkillTreeNames().contains(skillTree.getInheritance()))
{
inheritanceCheckBox.setSelected(true);
inheritanceComboBox.setEnabled(true);
this.inheritanceComboBoxModel.setSelectedItem(skillTree.getInheritance());
}
else
{
inheritanceComboBox.setEnabled(false);
}
}
skillTreeNameLabel.setText("Skilltree: " + skillTree.getName());
SortedDefaultMutableTreeNode rootNode = new SortedDefaultMutableTreeNode(skillTree.getName());
skillTreeTreeModel.setRoot(rootNode);
int skillcount = 0;
for (SkillTreeLevel level : skillTree.getLevelList())
{
highestLevel = Math.max(highestLevel, level.getLevel());
DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(level.getLevel());
rootNode.add(levelNode);
for (ISkillInfo skill : level.getSkills())
{
SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill);
levelNode.add(skillNode);
skillcount++;
}
}
if (skillcount <= 15)
{
for (int i = 0 ; i < skillTreeTree.getRowCount() ; i++)
{
skillTreeTree.expandRow(i);
}
}
else
{
skillTreeTree.expandRow(0);
}
skillTreeTree.updateUI();
skillTreeTree.setSelectionPath(new TreePath(rootNode));
}
private void createUIComponents()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode("");
skillTreeTreeModel = new DefaultTreeModel(root);
skillTreeTree = new JTree(skillTreeTreeModel);
skillTreeTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
inheritanceComboBoxModel = new DefaultComboBoxModel();
inheritanceComboBox = new JComboBox(inheritanceComboBoxModel);
}
private class SkillTreeSkillNode extends DefaultMutableTreeNode
{
private ISkillInfo skill;
public SkillTreeSkillNode(ISkillInfo skill)
{
super(skill.getName());
this.skill = skill;
}
public ISkillInfo getSkill()
{
return skill;
}
}
private class SortedDefaultMutableTreeNode extends DefaultMutableTreeNode
{
public SortedDefaultMutableTreeNode(Object userObject)
{
super(userObject);
}
@SuppressWarnings("unchecked")
public void add(DefaultMutableTreeNode newChild)
{
super.add(newChild);
Collections.sort(this.children, nodeComparator);
}
protected Comparator nodeComparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
if (Util.isInt(o1.toString()) && Util.isInt(o2.toString()))
{
int n1 = Integer.parseInt(o1.toString());
int n2 = Integer.parseInt(o2.toString());
if (n1 < n2)
{
return -1;
}
else if (n1 == n2)
{
return 0;
}
if (n1 > n2)
{
return 1;
}
}
return o1.toString().compareToIgnoreCase(o2.toString());
}
public boolean equals(Object obj)
{
return false;
}
};
}
}
| true | true | public LevelCreator()
{
if (skillNames == null)
{
skillNames = new String[SkillsInfo.getRegisteredSkillsInfo().size()];
int skillCounter = 0;
for (Class<? extends SkillTreeSkill> clazz : SkillsInfo.getRegisteredSkillsInfo())
{
SkillName sn = clazz.getAnnotation(SkillName.class);
if (sn != null)
{
skillNames[skillCounter++] = sn.value();
}
}
}
addLevelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = (String) JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE, null, null, "" + (highestLevel + 1));
if (response != null)
{
if (Util.isInt(response))
{
int newLevel = Integer.parseInt(response);
for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++)
{
if (Util.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()))
{
int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString());
if (newLevel == level)
{
JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
else if (newLevel < 1)
{
JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
highestLevel = Math.max(highestLevel, newLevel);
DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel);
skillTree.addLevel(newLevel);
((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode);
skillTreeTree.setSelectionPath(new TreePath(new Object[]{skillTreeTreeModel.getRoot(), levelNode}));
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
else
{
JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE);
}
}
}
});
addSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int level;
if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
}
else
{
return;
}
}
else
{
return;
}
String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, "");
if (choosenSkill != null)
{
ISkillInfo skill = SkillsInfo.getNewSkillInfoInstance(choosenSkill);
skillTree.addSkillToLevel(level, skill);
SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill);
skill.setDefaultProperties();
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode);
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
}
});
deleteLevelSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skillTreeTree.getSelectionPath().getPath().length == 2)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
skillTree.removeLevel(level);
}
else
{
return;
}
}
else if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2)));
skillTree.getLevel(level).removeSkill(index);
}
else
{
return;
}
}
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent();
skillTreeTree.updateUI();
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
}
});
skillTreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (e.getPath().getPath().length == 1)
{
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
else if (e.getPath().getPath().length == 2)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
if (level > 1 && skillTree.hasLevel(level))
{
levelUpMessageCheckBox.setEnabled(true);
selectedLevel = skillTree.getLevel(level);
if (selectedLevel.hasLevelupMessage())
{
levelUpMessageCheckBox.setSelected(true);
levelUpMessageInput.setEnabled(true);
levelUpMessageInput.setText(selectedLevel.getLevelupMessage());
}
else
{
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
}
}
}
}
else if (e.getPath().getPath().length == 3)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
}
});
inheritanceCheckBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (inheritanceCheckBox.isSelected())
{
inheritanceComboBox.setEnabled(true);
skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString());
}
else
{
inheritanceComboBox.setEnabled(false);
skillTree.setInheritance(null);
}
}
});
permissionCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (permissionCheckbox.isSelected())
{
permissionTextField.setEnabled(true);
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
}
else
{
permissionTextField.setEnabled(false);
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
});
displayNameCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (displayNameCheckbox.isSelected())
{
displayNameTextField.setEnabled(true);
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
else
{
displayNameTextField.setEnabled(false);
skillTree.setDisplayName(null);
}
}
});
backButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GuiMain.skilltreeCreator.getFrame().setEnabled(true);
levelCreatorFrame.setVisible(false);
}
});
inheritanceComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected())
{
if (!skillTree.getInheritance().equals(e.getItem().toString()))
{
skillTree.setInheritance(e.getItem().toString());
}
}
}
});
copyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
});
skillTreeTree.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode)
{
ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill();
if (skill.getClass().getAnnotation(SkillProperties.class) == null)
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (SkillsInfo.isValidSkill(skill.getName()))
{
if (skill.getGuiPanel() != null)
{
GuiMain.skillPropertyEditor.setSkill(skill);
}
else
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
GuiMain.skillPropertyEditor.getFrame().setVisible(true);
getFrame().setEnabled(false);
GuiMain.skillPropertyEditor.getFrame().setSize(GuiMain.skillPropertyEditor.getFrame().getWidth(), skill.getGuiPanel().getMainPanel().getHeight() + 90);
}
}
}
}
});
permissionTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", ""));
if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText()))
{
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
displayNameTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText()))
{
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageInput.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
if (levelUpMessageCheckBox.isSelected() && selectedLevel != null && !selectedLevel.getLevelupMessage().equals(levelUpMessageInput.getText()))
{
if (!levelUpMessageInput.getText().equalsIgnoreCase(""))
{
selectedLevel.setLevelupMessage(levelUpMessageInput.getText());
}
else
{
selectedLevel.setLevelupMessage(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageCheckBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
levelUpMessageInput.setEnabled(levelUpMessageCheckBox.isSelected());
}
});
}
| public LevelCreator()
{
if (skillNames == null)
{
skillNames = new String[SkillsInfo.getRegisteredSkillsInfo().size()];
int skillCounter = 0;
for (Class<? extends SkillTreeSkill> clazz : SkillsInfo.getRegisteredSkillsInfo())
{
SkillName sn = clazz.getAnnotation(SkillName.class);
if (sn != null)
{
skillNames[skillCounter++] = sn.value();
}
}
}
addLevelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String response = (String) JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE, null, null, "" + (highestLevel + 1));
if (response != null)
{
if (Util.isInt(response))
{
int newLevel = Integer.parseInt(response);
for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++)
{
if (Util.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()))
{
int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString());
if (newLevel == level)
{
JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
else if (newLevel < 1)
{
JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
highestLevel = Math.max(highestLevel, newLevel);
DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel);
skillTree.addLevel(newLevel);
((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode);
skillTreeTree.setSelectionPath(new TreePath(new Object[]{skillTreeTreeModel.getRoot(), levelNode}));
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
else
{
JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE);
}
}
}
});
addSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int level;
if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
}
else
{
return;
}
}
else
{
return;
}
String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, "");
if (choosenSkill != null)
{
ISkillInfo skill = SkillsInfo.getNewSkillInfoInstance(choosenSkill);
skillTree.addSkillToLevel(level, skill);
SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill);
skill.setDefaultProperties();
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode);
skillTreeTree.expandPath(skillTreeTree.getSelectionPath());
skillTreeTree.updateUI();
}
}
});
deleteLevelSkillButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (skillTreeTree.getSelectionPath().getPath().length == 2)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
skillTree.removeLevel(level);
}
else
{
return;
}
}
else if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (Util.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()))
{
short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString());
int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2)));
skillTree.getLevel(level).removeSkill(index);
}
else
{
return;
}
}
((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent();
skillTreeTree.updateUI();
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
}
});
skillTreeTree.addTreeSelectionListener(new TreeSelectionListener()
{
public void valueChanged(TreeSelectionEvent e)
{
if (e.getPath().getPath().length == 1)
{
addSkillButton.setEnabled(false);
deleteLevelSkillButton.setEnabled(false);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
else if (e.getPath().getPath().length == 2)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageInput.setText("");
if (Util.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()))
{
int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString());
if (level > 1 && skillTree.hasLevel(level))
{
levelUpMessageCheckBox.setEnabled(true);
selectedLevel = skillTree.getLevel(level);
if (selectedLevel.hasLevelupMessage())
{
levelUpMessageCheckBox.setSelected(true);
levelUpMessageInput.setEnabled(true);
levelUpMessageInput.setText(selectedLevel.getLevelupMessage());
}
else
{
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
}
}
}
}
else if (e.getPath().getPath().length == 3)
{
addSkillButton.setEnabled(true);
deleteLevelSkillButton.setEnabled(true);
levelUpMessageCheckBox.setEnabled(false);
levelUpMessageInput.setEnabled(false);
levelUpMessageCheckBox.setSelected(false);
levelUpMessageInput.setText("");
selectedLevel = null;
}
}
});
inheritanceCheckBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (inheritanceCheckBox.isSelected())
{
inheritanceComboBox.setEnabled(true);
skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString());
}
else
{
inheritanceComboBox.setEnabled(false);
skillTree.setInheritance(null);
}
}
});
permissionCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (permissionCheckbox.isSelected())
{
permissionTextField.setEnabled(true);
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
}
else
{
permissionTextField.setEnabled(false);
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
});
displayNameCheckbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (displayNameCheckbox.isSelected())
{
displayNameTextField.setEnabled(true);
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
else
{
displayNameTextField.setEnabled(false);
skillTree.setDisplayName(null);
}
}
});
backButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GuiMain.skilltreeCreator.getFrame().setEnabled(true);
levelCreatorFrame.setVisible(false);
}
});
inheritanceComboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected())
{
if (!skillTree.getInheritance().equals(e.getItem().toString()))
{
skillTree.setInheritance(e.getItem().toString());
}
}
}
});
copyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
});
skillTreeTree.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
if (skillTreeTree.getSelectionPath().getPath().length == 3)
{
if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode)
{
ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill();
if (skill.getClass().getAnnotation(SkillProperties.class) == null)
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (SkillsInfo.isValidSkill(skill.getName()))
{
if (skill.getGuiPanel() != null)
{
GuiMain.skillPropertyEditor.setSkill(skill);
}
else
{
JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
GuiMain.skillPropertyEditor.getFrame().setVisible(true);
getFrame().setEnabled(false);
GuiMain.skillPropertyEditor.getFrame().setSize(GuiMain.skillPropertyEditor.getFrame().getWidth(), skill.getGuiPanel().getMainPanel().getHeight() + 90);
}
}
}
}
});
permissionTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", ""));
if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText()))
{
if (!permissionTextField.getText().equalsIgnoreCase(""))
{
skillTree.setPermission(permissionTextField.getText());
}
else
{
skillTree.setPermission(null);
}
permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission());
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
displayNameTextField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText()))
{
if (!displayNameTextField.getText().equalsIgnoreCase(""))
{
skillTree.setDisplayName(displayNameTextField.getText());
}
else
{
skillTree.setDisplayName(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageInput.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent arg0)
{
}
public void keyReleased(KeyEvent arg0)
{
if (levelUpMessageCheckBox.isSelected() && selectedLevel != null && (selectedLevel.getLevelupMessage() == null || !selectedLevel.getLevelupMessage().equals(levelUpMessageInput.getText())))
{
if (!levelUpMessageInput.getText().equalsIgnoreCase(""))
{
selectedLevel.setLevelupMessage(levelUpMessageInput.getText());
}
else
{
selectedLevel.setLevelupMessage(null);
}
}
}
public void keyPressed(KeyEvent arg0)
{
}
});
levelUpMessageCheckBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
levelUpMessageInput.setEnabled(levelUpMessageCheckBox.isSelected());
}
});
}
|
diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java
index 3395c1bb92..a3d12b410e 100644
--- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java
+++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java
@@ -1,49 +1,49 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.scriptbuilder.domain;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
/**
* @author Adrian Cole
*/
@Test(groups = "unit")
public class UnzipHttpResponseIntoDirectoryToTest {
UnzipHttpResponseIntoDirectory jboss = new UnzipHttpResponseIntoDirectory(
"GET",
URI
.create("http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip"),
ImmutableMultimap.<String, String> of(), "/tmp");
public void testUnzipHttpResponseIntoDirectoryUNIX() {
assertEquals(
jboss.render(OsFamily.UNIX),
- "(mkdir -p /tmp &&cd /tmp &&curl -X GET -s --retry 20 http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\n");
+ "(mkdir -p /tmp &&cd /tmp &&curl -X -L GET -s --retry 20 http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\n");
}
public void testUnzipHttpResponseIntoDirectoryWINDOWS() {
jboss.render(OsFamily.WINDOWS); }
}
| true | true | public void testUnzipHttpResponseIntoDirectoryUNIX() {
assertEquals(
jboss.render(OsFamily.UNIX),
"(mkdir -p /tmp &&cd /tmp &&curl -X GET -s --retry 20 http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\n");
}
| public void testUnzipHttpResponseIntoDirectoryUNIX() {
assertEquals(
jboss.render(OsFamily.UNIX),
"(mkdir -p /tmp &&cd /tmp &&curl -X -L GET -s --retry 20 http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\n");
}
|
diff --git a/TinyTank/src/com/tiny/tank/Tank.java b/TinyTank/src/com/tiny/tank/Tank.java
index 54c4e0b..bf672aa 100644
--- a/TinyTank/src/com/tiny/tank/Tank.java
+++ b/TinyTank/src/com/tiny/tank/Tank.java
@@ -1,556 +1,558 @@
package com.tiny.tank;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.Renderable;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
import com.tiny.weapons.Shot;
/**
* Player class. Tanks
*/
public class Tank {
//Constants of size of tank
private final int tankWidth = 20;
private final int tankHeight = 10;
private final int barrelWidth = 8;
private final int barrelHeight = 3;
//animation end and the counter for it.
private final float animationLimit = 1;
private float animationCounter;
// stores the data of the player
private Vector2f pos;
// Angle of the player
private float barrelAng;
// previous angle of the player
private float prevAng;
private int direction;
private int health;
private int shotIndex;
// index of the player
private int index;
private ArrayList<Shot> shots;
private ArrayList<HUD> hud;
private Rectangle hitbox;
//Keeps an original incase resiszing must happen
private Image originalImage;
private Image image;
private Image originalBarrel;
private Image BarrelImage;
// x and y ranges of numbers. Will be usefull when we get rotations
private float[] xRange;
private float[] yRange;
//Only so much movement allowed per turn.
private int movementCounter;
private int movementLimit;
//States
private boolean isMoving;
private boolean isFalling;
private boolean isShooting;
//flag for if turn
private boolean isTurn;
/**
* Our good old players
*
* @param playerX
* X position of top right
* @param playerY
* Y position of top right
* @param barrelAng
* The angle of the barrel
* @param health
* Player health
* @param shots
* List of weapons
* @param index
* Player number
*/
public void TankInfo(float playerX, float playerY, float barrelAng,
int health, ArrayList<Shot> shots, int index) {
this.pos = new Vector2f(playerX, playerY);
this.barrelAng = barrelAng;
this.prevAng = barrelAng;
this.health = health;
this.index = index;
this.shots = shots;
this.hud = hud;
// player1 looks right, player 2 looks left
if (index == 1) {
direction = 1;
try {
//tank
originalImage = new Image("res/BlueTank.png");
originalImage.setFilter(Image.FILTER_NEAREST);
image = originalImage.getScaledCopy(tankWidth, tankHeight);
//barrel (seperate so it can change angle)
originalBarrel = new Image("res/BlueBarrel.png");
originalBarrel.setFilter(Image.FILTER_NEAREST);
BarrelImage = originalBarrel.getScaledCopy(tankWidth,tankHeight);
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
direction = -1;
try {
originalImage = new Image("res/RedTank.png");
originalImage.setFilter(Image.FILTER_NEAREST);
image = originalImage.getScaledCopy(tankWidth, tankHeight);
//barrel (seperate so it can change angle)
originalBarrel = new Image("res/RedBarrel.png");
originalBarrel.setFilter(Image.FILTER_NEAREST);
BarrelImage = originalBarrel.getScaledCopy(tankWidth, tankHeight);
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//sets states
isMoving = false;
isFalling = false;
isShooting = false;
//sets range and hitbox
hitbox = new Rectangle(playerX, playerY, tankWidth, tankHeight);
xRange = new float[2];
yRange = new float[2];
xRange = calculateXRange(hitbox);
yRange = calculateYRange(hitbox);
//initilizies player 1 to go first;
if(index == 1){
onTurnSwitch();
}else{
isTurn = false;
}
//start animation over
animationCounter = 0;
setFirstPos();
}
/**
* Will set the position upon map creation. Puts it right on top of map
*/
public void setFirstPos() {
pos.y = Main_Gameplay.map.getMaxInRange(xRange[0], xRange[1])
- tankHeight + 0;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
}
/**
* takes care of things that happen on switch of turns. Also resets movement limit here.
* This will allow for speed based attacks later (such as a movement booster).
*/
public void onTurnSwitch() {
movementCounter = 0;
animationCounter = 0;
movementLimit = 80;
isTurn = true;
shotIndex = 0;
}
/**
* What to do when done.
* Currently shot calls this when done.
*/
public void shotDone(){
if(isShooting){
isShooting = false;
isFalling = true;
shots.remove(shotIndex);
turnEnd();
}else{
isFalling = true;
}
}
/**
* Clean up for when turn is over.
*/
public void turnEnd(){
isTurn = false;
}
/**
* Will update the events relating to tanks and shots
*/
public void update(GameContainer container, Camera cam) {
Input input = container.getInput();
// state handeling if falling
if (isFalling) {
isMoving = false;
animationCounter += 1;
if (animationCounter > animationLimit) {
pos.y += 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
if (checkCollision(pos)) {
pos.y -= 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
isFalling = false;
animationCounter = 0;
}
animationCounter -= animationLimit;
}
}
// state handeling if shooting
if (isShooting) {
for (int i = 0; i < shots.size(); i++) {
if (shots.get(i).isShot()) {
shots.get(i).update(container);
}
}
}
//will execute if sitting essentially
if(!isShooting && !isFalling && !isMoving && isTurn)
{
//if the shoot key is pushed, initilize shot and start shooting
if(input.isKeyPressed(Input.KEY_SPACE)){
getShots().get(shotIndex).init(new Vector2f(hitbox.getCenterX(),hitbox.getCenterY()),new Vector2f(2*direction,5));
setShooting(true);
}
BarrelImage.setCenterOfRotation(BarrelImage.getWidth()/2,BarrelImage.getHeight());
// angle the barrel up
if(input.isKeyDown(Input.KEY_W))
{
- System.out.println(BarrelImage.getRotation());
+ //System.out.println(BarrelImage.getRotation());
// if its facing left
if (direction == -1)
{
if(BarrelImage.getRotation() < 90)
BarrelImage.rotate(1);
}
// facing right
if (direction == 1)
{
if(BarrelImage.getRotation() > -90)
BarrelImage.rotate(-1);
}
}
// angle the barrel Down
if(input.isKeyDown(Input.KEY_S))
{
- System.out.println(BarrelImage.getRotation());
+/// System.out.println(BarrelImage.getRotation());
// facing left
if (direction == -1)
{
if(BarrelImage.getRotation() > -30) // set lower limit
BarrelImage.rotate(-1);
}
// facing right
if (direction == 1)
{
- if(BarrelImage.getRotation() < 30); // set lower limit
- BarrelImage.rotate(1);
+ if(BarrelImage.getRotation() <30){ // set lower limit
+ System.out.println(BarrelImage.getRotation());
+ BarrelImage.rotate(1);
+ }
}
}
}
/*for(int i = 0; i < hud.size(); i++) {
hud.get(i).update();
}*/
//hud.get(0).update();
}
/**
* Takes care of movement of tank.
* @param input
*/
public void move(Input input) {
//wont move is shooting or falling
if (!isShooting && !isFalling) {
//checks if player has used all movement alloted this turn
if (movementCounter < movementLimit) {
float tankMovement = .5f;
if (input.isKeyDown(Input.KEY_A)) {
movementCounter += 1;
isMoving = true;
pos = movePos(-tankMovement, 0);
isFalling = true;
} else if (input.isKeyDown(Input.KEY_D)) {
movementCounter += 1;
isMoving = true;
pos = movePos(tankMovement, 0);
isFalling = true;
} else {
isMoving = false;
}
}else{
isMoving = false;
}
}
}
/**
* Does the actual movement and returns new position.
* Moves and then resolves collision.
* If height change is too much, will return old pos.
* @param x Amount to move in the x direction
* @param y Amount to move in the y drection
* @return the new position
*/
private Vector2f movePos(float x, float y) {
Vector2f tempPos = pos.copy();
tempPos.x += x;
tempPos.y += y;
int tolerance = 2;
for (int i = 0; i < tolerance; i++) {
if (checkCollision(tempPos)) {
tempPos.y -= 1;
} else {
return tempPos;
}
}
return pos;
}
/**
* Anything needed to render the tanks goes here.
*
* @param container
* @param game
* @param g
*/
public void render(GameContainer container, StateBasedGame game, Graphics g, Camera cam) {
// current graphical representation
BarrelImage.setCenterOfRotation(BarrelImage.getWidth()/2*cam.getScale(),BarrelImage.getHeight()/2*cam.getScale());
BarrelImage.draw(cam.transformScreenToCamX(pos.x), cam.transformScreenToCamY(pos.y), cam.getScale());
//tank
image.draw(cam.transformScreenToCamX(pos.x), cam.transformScreenToCamY(pos.y), cam.getScale());
//barrel
//BarrelImage.draw(cam.transformScreenToCamX(pos.x+hitbox.getWidth()/2), cam.transformScreenToCamY(pos.y+hitbox.getHeight()/2), cam.getScale());
if(isShooting){
getShots().get(shotIndex).render(container, game, g, cam);
}
}
/**
* Checks if tanks collide with terrain
*
* @return
*/
public boolean checkCollision(Vector2f pos) {
Rectangle hitbox = new Rectangle(pos.x, pos.y, tankWidth, tankHeight);
float[] xRange = calculateXRange(hitbox);
float[] yRange = calculateYRange(hitbox);
// checks if outside the map
if (hitbox.getMaxX() > Main_Gameplay.map.getWidth() - 1
|| hitbox.getMinX() < 0
|| hitbox.getMaxY() > Main_Gameplay.map.getHeight() - 1
|| hitbox.getMinY() < 0) {
return true;
}
// gets teh highest point under the tank
int mapMaxInRange = Main_Gameplay.map.getMaxInRange(xRange[0],
xRange[1]);
// if lowest corner is below mapmax does collision check
if (yRange[1] > mapMaxInRange) {
for (int i = (int) xRange[0]; i < xRange[1]; i++) {
for (int j = (int) yRange[0]; j < yRange[1]; j++) {
if (Main_Gameplay.map.collision(new Vector2f(i, j))) {
if (hitbox.contains(i, j)) {
return true;
}
}
}
}
}
return false;
}
/**
* recalculates range if needs to
*/
/*
* private void checkRange() { if (!hasRangeChanged) { return; }
*
* calculateXRange(); calculateYRange(); }
*/
private float[] calculateXRange(Rectangle hitbox) {
float left = hitbox.getMinX();
float right = hitbox.getMaxX();
float[] xRange = new float[2];
xRange[0] = left;
xRange[1] = right;
return xRange;
}
private float[] calculateYRange(Rectangle hitbox) {
float top = hitbox.getMinY();
float bottom = hitbox.getMaxY();
float[] yRange = new float[2];
yRange[0] = top;
yRange[1] = bottom;
return yRange;
}
/**
* series of gets and sets to assign the variables of the tank
* the given and calculated values
*/
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public ArrayList<Shot> getShots() {
return shots;
}
public void setShots(ArrayList<Shot> shots) {
this.shots = shots;
}
public ArrayList<HUD> getHud() {
return hud;
}
public void setHud(ArrayList<HUD> hud) {
this.hud = hud;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public float getPlayerDir() {
return barrelAng;
}
public void setPlayerDir(int playerDir) {
prevAng = this.barrelAng;
this.barrelAng = playerDir;
}
public float getPrevDir() {
return prevAng;
}
public boolean isAlive() {
return health > 0 ? true : false;
}
public boolean isShooting() {
return isShooting;
}
public void setShooting(boolean isShooting) {
this.isShooting = isShooting;
}
public Vector2f getPos() {
return pos;
}
public void setPos(Vector2f pos) {
this.pos = pos;
}
public float getBarrelAng() {
return barrelAng;
}
public void setBarrelAng(float barrelAng) {
this.barrelAng = barrelAng;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public Rectangle getHitbox() {
return hitbox;
}
public void setHitbox(Rectangle hitbox) {
this.hitbox = hitbox;
}
public boolean isMoving() {
return isMoving;
}
public void setMoving(boolean isMoving) {
this.isMoving = isMoving;
}
public boolean isFalling() {
return isFalling;
}
public void setFalling(boolean isFalling) {
this.isFalling = isFalling;
}
public boolean isTurn() {
return isTurn;
}
public void setTurn(boolean isTurn) {
this.isTurn = isTurn;
}
}
| false | true | public void update(GameContainer container, Camera cam) {
Input input = container.getInput();
// state handeling if falling
if (isFalling) {
isMoving = false;
animationCounter += 1;
if (animationCounter > animationLimit) {
pos.y += 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
if (checkCollision(pos)) {
pos.y -= 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
isFalling = false;
animationCounter = 0;
}
animationCounter -= animationLimit;
}
}
// state handeling if shooting
if (isShooting) {
for (int i = 0; i < shots.size(); i++) {
if (shots.get(i).isShot()) {
shots.get(i).update(container);
}
}
}
//will execute if sitting essentially
if(!isShooting && !isFalling && !isMoving && isTurn)
{
//if the shoot key is pushed, initilize shot and start shooting
if(input.isKeyPressed(Input.KEY_SPACE)){
getShots().get(shotIndex).init(new Vector2f(hitbox.getCenterX(),hitbox.getCenterY()),new Vector2f(2*direction,5));
setShooting(true);
}
BarrelImage.setCenterOfRotation(BarrelImage.getWidth()/2,BarrelImage.getHeight());
// angle the barrel up
if(input.isKeyDown(Input.KEY_W))
{
System.out.println(BarrelImage.getRotation());
// if its facing left
if (direction == -1)
{
if(BarrelImage.getRotation() < 90)
BarrelImage.rotate(1);
}
// facing right
if (direction == 1)
{
if(BarrelImage.getRotation() > -90)
BarrelImage.rotate(-1);
}
}
// angle the barrel Down
if(input.isKeyDown(Input.KEY_S))
{
System.out.println(BarrelImage.getRotation());
// facing left
if (direction == -1)
{
if(BarrelImage.getRotation() > -30) // set lower limit
BarrelImage.rotate(-1);
}
// facing right
if (direction == 1)
{
if(BarrelImage.getRotation() < 30); // set lower limit
BarrelImage.rotate(1);
}
}
}
/*for(int i = 0; i < hud.size(); i++) {
hud.get(i).update();
}*/
| public void update(GameContainer container, Camera cam) {
Input input = container.getInput();
// state handeling if falling
if (isFalling) {
isMoving = false;
animationCounter += 1;
if (animationCounter > animationLimit) {
pos.y += 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
if (checkCollision(pos)) {
pos.y -= 1;
hitbox.setBounds(pos.x, pos.y, tankWidth, tankHeight);
isFalling = false;
animationCounter = 0;
}
animationCounter -= animationLimit;
}
}
// state handeling if shooting
if (isShooting) {
for (int i = 0; i < shots.size(); i++) {
if (shots.get(i).isShot()) {
shots.get(i).update(container);
}
}
}
//will execute if sitting essentially
if(!isShooting && !isFalling && !isMoving && isTurn)
{
//if the shoot key is pushed, initilize shot and start shooting
if(input.isKeyPressed(Input.KEY_SPACE)){
getShots().get(shotIndex).init(new Vector2f(hitbox.getCenterX(),hitbox.getCenterY()),new Vector2f(2*direction,5));
setShooting(true);
}
BarrelImage.setCenterOfRotation(BarrelImage.getWidth()/2,BarrelImage.getHeight());
// angle the barrel up
if(input.isKeyDown(Input.KEY_W))
{
//System.out.println(BarrelImage.getRotation());
// if its facing left
if (direction == -1)
{
if(BarrelImage.getRotation() < 90)
BarrelImage.rotate(1);
}
// facing right
if (direction == 1)
{
if(BarrelImage.getRotation() > -90)
BarrelImage.rotate(-1);
}
}
// angle the barrel Down
if(input.isKeyDown(Input.KEY_S))
{
/// System.out.println(BarrelImage.getRotation());
// facing left
if (direction == -1)
{
if(BarrelImage.getRotation() > -30) // set lower limit
BarrelImage.rotate(-1);
}
// facing right
if (direction == 1)
{
if(BarrelImage.getRotation() <30){ // set lower limit
System.out.println(BarrelImage.getRotation());
BarrelImage.rotate(1);
}
}
}
}
/*for(int i = 0; i < hud.size(); i++) {
hud.get(i).update();
}*/
|
diff --git a/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/EditConnectorConfigurationWizard.java b/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/EditConnectorConfigurationWizard.java
index 08ce0a7558..f450bea229 100644
--- a/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/EditConnectorConfigurationWizard.java
+++ b/plugins/org.bonitasoft.studio.connectors/src/org/bonitasoft/studio/connectors/ui/wizard/EditConnectorConfigurationWizard.java
@@ -1,105 +1,105 @@
/**
* 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.connectors.ui.wizard;
import java.util.Set;
import org.bonitasoft.studio.common.repository.RepositoryManager;
import org.bonitasoft.studio.common.repository.filestore.DefinitionConfigurationFileStore;
import org.bonitasoft.studio.connector.model.definition.ConnectorDefinition;
import org.bonitasoft.studio.connectors.repository.ConnectorConfRepositoryStore;
import org.bonitasoft.studio.connectors.repository.ConnectorDefRepositoryStore;
import org.bonitasoft.studio.connectors.ui.wizard.page.SelectConnectorConfigurationWizardPage;
import org.bonitasoft.studio.model.connectorconfiguration.ConnectorConfiguration;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.jface.wizard.IWizardPage;
/**
* @author Aurelie Zara
*
*/
public class EditConnectorConfigurationWizard extends ConnectorWizard {
private SelectConnectorConfigurationWizardPage selectConfigurationPage;
private ConnectorDefRepositoryStore connectorDefStore;
private ConnectorConfRepositoryStore connectorConfStore;
public EditConnectorConfigurationWizard(EObject container,EStructuralFeature connectorContainmentFeature ,Set<EStructuralFeature> featureToCheckForUniqueID){
super(container,connectorContainmentFeature,featureToCheckForUniqueID);
setEditMode(false);
connectorDefStore = (ConnectorDefRepositoryStore) RepositoryManager.getInstance().getRepositoryStore(ConnectorDefRepositoryStore.class) ;
connectorConfStore = (ConnectorConfRepositoryStore) RepositoryManager.getInstance().getRepositoryStore(ConnectorConfRepositoryStore.class);
setForcePreviousAndNextButtons(true);
}
/* (non-Javadoc)
* @see org.bonitasoft.studio.connectors.ui.wizard.ConnectorWizard#addPages()
*/
@Override
public void addPages() {
selectConfigurationPage = new SelectConnectorConfigurationWizardPage();
addPage(selectConfigurationPage);
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
if(page.equals(selectConfigurationPage)){
final ConnectorConfiguration conf = selectConfigurationPage.getSelectedConfiguration();
if(conf != null){
ConnectorDefinition definition = connectorDefStore.getDefinition(conf.getDefinitionId(), conf.getVersion());
connectorWorkingCopy.setDefinitionId(definition.getId());
connectorWorkingCopy.setDefinitionVersion(definition.getVersion());
checkDefinitionDependencies(definition) ;
connectorWorkingCopy.setConfiguration(conf);
extension = findCustomWizardExtension(definition) ;
- recreateConnectorConfigurationPages(definition,true);
+ recreateConnectorConfigurationPages(definition,false);
}
}
return super.getNextPage(page);
}
/* (non-Javadoc)
* @see org.bonitasoft.studio.connectors.ui.wizard.ConnectorWizard#addNameAndDescriptionPage()
*/
@Override
protected void addNameAndDescriptionPage() {
}
/* (non-Javadoc)
* @see org.bonitasoft.studio.connectors.ui.wizard.ConnectorWizard#addOuputPage(org.bonitasoft.studio.connector.model.definition.ConnectorDefinition)
*/
@Override
protected void addOuputPage(ConnectorDefinition definition) {
}
@Override
public boolean performFinish() {
ConnectorConfiguration conf = connectorWorkingCopy.getConfiguration();
DefinitionConfigurationFileStore fileStore = connectorConfStore.getChild(conf.getName()+"."+ConnectorConfRepositoryStore.CONF_EXT);
fileStore.save(conf);
return true;
}
}
| true | true | public IWizardPage getNextPage(IWizardPage page) {
if(page.equals(selectConfigurationPage)){
final ConnectorConfiguration conf = selectConfigurationPage.getSelectedConfiguration();
if(conf != null){
ConnectorDefinition definition = connectorDefStore.getDefinition(conf.getDefinitionId(), conf.getVersion());
connectorWorkingCopy.setDefinitionId(definition.getId());
connectorWorkingCopy.setDefinitionVersion(definition.getVersion());
checkDefinitionDependencies(definition) ;
connectorWorkingCopy.setConfiguration(conf);
extension = findCustomWizardExtension(definition) ;
recreateConnectorConfigurationPages(definition,true);
}
}
return super.getNextPage(page);
}
| public IWizardPage getNextPage(IWizardPage page) {
if(page.equals(selectConfigurationPage)){
final ConnectorConfiguration conf = selectConfigurationPage.getSelectedConfiguration();
if(conf != null){
ConnectorDefinition definition = connectorDefStore.getDefinition(conf.getDefinitionId(), conf.getVersion());
connectorWorkingCopy.setDefinitionId(definition.getId());
connectorWorkingCopy.setDefinitionVersion(definition.getVersion());
checkDefinitionDependencies(definition) ;
connectorWorkingCopy.setConfiguration(conf);
extension = findCustomWizardExtension(definition) ;
recreateConnectorConfigurationPages(definition,false);
}
}
return super.getNextPage(page);
}
|
diff --git a/src/main/java/com/beayoscar/babynames/web/NameController.java b/src/main/java/com/beayoscar/babynames/web/NameController.java
index 1220eff..00a8903 100644
--- a/src/main/java/com/beayoscar/babynames/web/NameController.java
+++ b/src/main/java/com/beayoscar/babynames/web/NameController.java
@@ -1,45 +1,45 @@
package com.beayoscar.babynames.web;
import java.util.Collection;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.beayoscar.babynames.domain.Name;
@RooWebScaffold(path = "names", formBackingObject = Name.class)
@RequestMapping("/names")
@Controller
public class NameController {
@ModelAttribute("names")
public Collection<Name> populateNames() {
//return Name.findAllNames();
return null;
}
@RequestMapping(value = "/listgenders", method = RequestMethod.GET)
public String list(Model uiModel) {
return "names/listbygender";
}
@RequestMapping(value = "/{id}/liked", method = RequestMethod.PUT, headers = "Accept=application/json")
- public ResponseEntity<String> updateFromJsonw(@PathVariable("id") Long id) {
+ public ResponseEntity<String> likeName(@PathVariable("id") Long id) {
Name name = Name.findName(id);
name.setVote(name.getVote() + 1);
HttpHeaders headers= new HttpHeaders();
headers.add("Content-Type", "application/text");
if (name.merge() == null) {
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(name.toJson(), headers, HttpStatus.OK);
}
}
| true | true | public ResponseEntity<String> updateFromJsonw(@PathVariable("id") Long id) {
Name name = Name.findName(id);
name.setVote(name.getVote() + 1);
HttpHeaders headers= new HttpHeaders();
headers.add("Content-Type", "application/text");
if (name.merge() == null) {
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(name.toJson(), headers, HttpStatus.OK);
}
| public ResponseEntity<String> likeName(@PathVariable("id") Long id) {
Name name = Name.findName(id);
name.setVote(name.getVote() + 1);
HttpHeaders headers= new HttpHeaders();
headers.add("Content-Type", "application/text");
if (name.merge() == null) {
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(name.toJson(), headers, HttpStatus.OK);
}
|
diff --git a/src/java/com/threerings/config/dist/server/DConfigManager.java b/src/java/com/threerings/config/dist/server/DConfigManager.java
index 1b4da2cd..76defdeb 100644
--- a/src/java/com/threerings/config/dist/server/DConfigManager.java
+++ b/src/java/com/threerings/config/dist/server/DConfigManager.java
@@ -1,127 +1,134 @@
//
// $Id$
//
// Clyde library - tools for developing networked games
// Copyright (C) 2005-2009 Three Rings Design, Inc.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.threerings.config.dist.server;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.threerings.presents.annotation.EventThread;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.server.InvocationManager;
import com.threerings.presents.server.PresentsDObjectMgr;
import com.threerings.crowd.data.BodyObject;
import com.threerings.config.ConfigManager;
import com.threerings.config.dist.data.ConfigEntry;
import com.threerings.config.dist.data.ConfigKey;
import com.threerings.config.dist.data.DConfigObject;
import com.threerings.config.dist.util.ConfigUpdater;
import static com.threerings.ClydeLog.*;
/**
* Handles the server side of the distributed config system.
*/
@Singleton @EventThread
public class DConfigManager
implements DConfigProvider
{
/**
* Creates a new config manager.
*/
@Inject public DConfigManager (
ConfigManager cfgmgr, PresentsDObjectMgr omgr, InvocationManager invmgr)
{
omgr.registerObject(_cfgobj = new DConfigObject());
_cfgobj.dconfigService = invmgr.registerDispatcher(new DConfigDispatcher(this));
new ConfigUpdater(cfgmgr).init(_cfgobj);
}
/**
* Returns a reference to the config object.
*/
public DConfigObject getConfigObject ()
{
return _cfgobj;
}
// documentation inherited from interface DConfigProvider
public void updateConfigs (
ClientObject caller, ConfigEntry[] add, ConfigEntry[] update, ConfigKey[] remove)
{
// make sure they're an admin
if (!((BodyObject)caller).getTokens().isAdmin()) {
log.warning("Non-admin tried to update configs.", "who", caller.who());
return;
}
int cloid = caller.getOid();
_cfgobj.startTransaction();
try {
// add the requested configs
for (ConfigEntry entry : add) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.removed.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
- _cfgobj.requestEntryAdd(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
+ if (_cfgobj.added.containsKey(key)) {
+ _cfgobj.requestEntryUpdate(
+ DConfigObject.ADDED, _cfgobj.added, entry, cloid);
+ } else {
+ _cfgobj.requestEntryAdd(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
+ }
}
}
// update the requested configs
for (ConfigEntry entry : update) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryUpdate(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
} else if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryUpdate(
DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
}
}
// remove the requested configs
for (ConfigKey key : remove) {
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.ADDED, _cfgobj.added, key, cloid);
} else {
if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryRemove(
DConfigObject.UPDATED, _cfgobj.updated, key, cloid);
}
- _cfgobj.requestEntryAdd(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
+ if (!_cfgobj.removed.containsKey(key)) {
+ _cfgobj.requestEntryAdd(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
+ }
}
}
} finally {
_cfgobj.commitTransaction();
}
}
/** The config object. */
protected DConfigObject _cfgobj;
}
| false | true | public void updateConfigs (
ClientObject caller, ConfigEntry[] add, ConfigEntry[] update, ConfigKey[] remove)
{
// make sure they're an admin
if (!((BodyObject)caller).getTokens().isAdmin()) {
log.warning("Non-admin tried to update configs.", "who", caller.who());
return;
}
int cloid = caller.getOid();
_cfgobj.startTransaction();
try {
// add the requested configs
for (ConfigEntry entry : add) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.removed.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
_cfgobj.requestEntryAdd(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
}
}
// update the requested configs
for (ConfigEntry entry : update) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryUpdate(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
} else if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryUpdate(
DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
}
}
// remove the requested configs
for (ConfigKey key : remove) {
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.ADDED, _cfgobj.added, key, cloid);
} else {
if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryRemove(
DConfigObject.UPDATED, _cfgobj.updated, key, cloid);
}
_cfgobj.requestEntryAdd(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
}
}
} finally {
_cfgobj.commitTransaction();
}
}
| public void updateConfigs (
ClientObject caller, ConfigEntry[] add, ConfigEntry[] update, ConfigKey[] remove)
{
// make sure they're an admin
if (!((BodyObject)caller).getTokens().isAdmin()) {
log.warning("Non-admin tried to update configs.", "who", caller.who());
return;
}
int cloid = caller.getOid();
_cfgobj.startTransaction();
try {
// add the requested configs
for (ConfigEntry entry : add) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.removed.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryUpdate(
DConfigObject.ADDED, _cfgobj.added, entry, cloid);
} else {
_cfgobj.requestEntryAdd(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
}
}
}
// update the requested configs
for (ConfigEntry entry : update) {
ConfigKey key = (ConfigKey)entry.getKey();
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryUpdate(DConfigObject.ADDED, _cfgobj.added, entry, cloid);
} else if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryUpdate(
DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
} else {
_cfgobj.requestEntryAdd(DConfigObject.UPDATED, _cfgobj.updated, entry, cloid);
}
}
// remove the requested configs
for (ConfigKey key : remove) {
if (_cfgobj.added.containsKey(key)) {
_cfgobj.requestEntryRemove(DConfigObject.ADDED, _cfgobj.added, key, cloid);
} else {
if (_cfgobj.updated.containsKey(key)) {
_cfgobj.requestEntryRemove(
DConfigObject.UPDATED, _cfgobj.updated, key, cloid);
}
if (!_cfgobj.removed.containsKey(key)) {
_cfgobj.requestEntryAdd(DConfigObject.REMOVED, _cfgobj.removed, key, cloid);
}
}
}
} finally {
_cfgobj.commitTransaction();
}
}
|
diff --git a/deegree2-core/src/main/java/org/deegree/enterprise/servlet/SimpleProxyServlet.java b/deegree2-core/src/main/java/org/deegree/enterprise/servlet/SimpleProxyServlet.java
index 2a39e4c..2ca5f55 100644
--- a/deegree2-core/src/main/java/org/deegree/enterprise/servlet/SimpleProxyServlet.java
+++ b/deegree2-core/src/main/java/org/deegree/enterprise/servlet/SimpleProxyServlet.java
@@ -1,269 +1,270 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.enterprise.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.deegree.enterprise.WebUtils;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
import org.deegree.framework.util.CharsetUtils;
import org.deegree.framework.util.KVP2Map;
import org.deegree.framework.util.StringTools;
import org.deegree.i18n.Messages;
import org.deegree.ogcwebservices.OGCRequestFactory;
import org.deegree.ogcwebservices.OGCWebServiceException;
import org.deegree.ogcwebservices.OGCWebServiceRequest;
/**
* simple proxy servlet The servlet is intended to run in its own context combined with ServletFilter (e.g.
* OWSProxyServletFilter ) to filter out invalid requests/responses
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Andreas Poth </a>
* @author last edited by: $Author$
*
* @version 1.0. $Revision$, $Date$
*
* @since 1.1
*/
public class SimpleProxyServlet extends HttpServlet {
private ILogger LOG = LoggerFactory.getLogger( SimpleProxyServlet.class );
private static final long serialVersionUID = 3086952074808203858L;
private Map<String, String> host = null;
private boolean removeCredentials = false;
/**
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init()
throws ServletException {
super.init();
host = new HashMap<String, String>();
Enumeration<?> enu = getInitParameterNames();
while ( enu.hasMoreElements() ) {
String pn = (String) enu.nextElement();
if ( pn.toLowerCase().equals( "removecredentials" ) ) {
removeCredentials = getInitParameter( pn ).equalsIgnoreCase( "true" );
continue;
}
String[] tmp = StringTools.toArray( pn, ":", false );
String hostAddr = this.getInitParameter( pn );
host.put( tmp[0], hostAddr );
}
}
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
InputStream is = null;
OutputStream os = null;
try {
String query = request.getQueryString();
Map<String, String> map = KVP2Map.toMap( query );
if ( removeCredentials ) {
map.remove( "USER" );
map.remove( "PASSWORD" );
map.remove( "SESSIONID" );
query = "";
for ( String key : map.keySet() ) {
query += key + "=" + map.get( key ) + "&";
}
query = query.substring( 0, query.length() - 1 );
}
String service = getService( map );
String hostAddr = host.get( service );
String req = hostAddr + "?" + query;
URL url = new URL( req );
LOG.logDebug( "forward URL: " + url );
URLConnection con = url.openConnection();
con.setDoInput( true );
con.setDoOutput( false );
is = con.getInputStream();
response.setContentType( con.getContentType() );
response.setCharacterEncoding( con.getContentEncoding() );
os = response.getOutputStream();
int read = 0;
byte[] buf = new byte[16384];
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
- LOG.logDebug( new String( buf, 0, read, con.getContentEncoding() ) );
+ LOG.logDebug( new String( buf, 0, read, con.getContentEncoding() == null ? "UTF-8"
+ : con.getContentEncoding() ) );
}
} else {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
}
}
} catch ( Exception e ) {
e.printStackTrace();
response.setContentType( "text/plain; charset=" + CharsetUtils.getSystemCharset() );
os.write( StringTools.stackTraceToString( e ).getBytes() );
} finally {
try {
is.close();
} catch ( Exception e ) {
// try to do what ?
}
try {
os.close();
} catch ( Exception e ) {
// try to do what ?
}
}
}
/**
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost( HttpServletRequest origReq, HttpServletResponse response )
throws ServletException, IOException {
// wrap request to enable access of the requests InputStream more
// than one time
ServletRequestWrapper request = new ServletRequestWrapper( origReq );
OutputStream os = null;
try {
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
// because this is an expensive operation it just will
// performed if debug level is set too DEBUG
InputStream reqIs = request.getInputStream();
StringBuffer sb = new StringBuffer( 10000 );
int c = 0;
while ( ( c = reqIs.read() ) > -1 ) {
sb.append( (char) c );
}
reqIs.close();
LOG.logDebug( "Request: " + sb );
}
OGCWebServiceRequest req = OGCRequestFactory.create( request );
String hostAddr = host.get( req.getServiceName() );
LOG.logDebug( "forward URL: " + hostAddr );
if ( hostAddr == null ) {
throw new Exception( Messages.getMessage( "PROXY_SERVLET_UNDEFINED_HOST", req.getServiceName() ) );
}
// determine charset for setting request content type
// use system charset if no charset can be determined
// from incoming request
String charset = origReq.getCharacterEncoding();
LOG.logDebug( "request character encoding: ", charset );
if ( charset == null ) {
charset = CharsetUtils.getSystemCharset();
LOG.logDebug( "use sytem character encoding: ", charset );
}
HttpClient client = new HttpClient();
client = WebUtils.enableProxyUsage( client, new URL( hostAddr ) );
PostMethod post = new PostMethod( hostAddr );
post.setRequestHeader( "Content-type", "text/xml; charset=" + charset );
post.setRequestEntity( new InputStreamRequestEntity( request.getInputStream() ) );
client.executeMethod( post );
LOG.logDebug( "Content-type: ", post.getResponseHeader( "Content-type" ) );
os = response.getOutputStream();
os.write( post.getResponseBody() );
} catch ( Exception e ) {
e.printStackTrace();
response.setContentType( "text/plain; charset=" + CharsetUtils.getSystemCharset() );
os.write( StringTools.stackTraceToString( e ).getBytes() );
} finally {
try {
os.close();
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
/**
* @return the name of the service that is targeted by the passed KVP encoded request
*
* @param map
* @throws Exception
*/
private String getService( Map<String, String> map )
throws Exception {
String service = null;
String req = map.get( "REQUEST" );
if ( "WMS".equals( map.get( "SERVICE" ) ) || req.equals( "GetMap" ) || req.equals( "GetFeatureInfo" )
|| req.equals( "GetLegendGraphic" ) ) {
service = "WMS";
} else if ( "WFS".equals( map.get( "SERVICE" ) ) || req.equals( "DescribeFeatureType" )
|| req.equals( "GetFeature" ) ) {
service = "WFS";
} else if ( "WCS".equals( map.get( "SERVICE" ) ) || req.equals( "GetCoverage" )
|| req.equals( "DescribeCoverage" ) ) {
service = "WCS";
} else if ( "CSW".equals( map.get( "SERVICE" ) ) || req.equals( "GetRecords" ) || req.equals( "GetRecordById" )
|| req.equals( "Harvest" ) || req.equals( "DescribeRecord" ) ) {
service = "CSW";
} else {
throw new OGCWebServiceException( "unknown service/request: " + map.get( "SERVICE" ) );
}
return service;
}
}
| true | true | protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
InputStream is = null;
OutputStream os = null;
try {
String query = request.getQueryString();
Map<String, String> map = KVP2Map.toMap( query );
if ( removeCredentials ) {
map.remove( "USER" );
map.remove( "PASSWORD" );
map.remove( "SESSIONID" );
query = "";
for ( String key : map.keySet() ) {
query += key + "=" + map.get( key ) + "&";
}
query = query.substring( 0, query.length() - 1 );
}
String service = getService( map );
String hostAddr = host.get( service );
String req = hostAddr + "?" + query;
URL url = new URL( req );
LOG.logDebug( "forward URL: " + url );
URLConnection con = url.openConnection();
con.setDoInput( true );
con.setDoOutput( false );
is = con.getInputStream();
response.setContentType( con.getContentType() );
response.setCharacterEncoding( con.getContentEncoding() );
os = response.getOutputStream();
int read = 0;
byte[] buf = new byte[16384];
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
LOG.logDebug( new String( buf, 0, read, con.getContentEncoding() ) );
}
} else {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
}
}
} catch ( Exception e ) {
e.printStackTrace();
response.setContentType( "text/plain; charset=" + CharsetUtils.getSystemCharset() );
os.write( StringTools.stackTraceToString( e ).getBytes() );
} finally {
try {
is.close();
} catch ( Exception e ) {
// try to do what ?
}
try {
os.close();
} catch ( Exception e ) {
// try to do what ?
}
}
}
| protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
InputStream is = null;
OutputStream os = null;
try {
String query = request.getQueryString();
Map<String, String> map = KVP2Map.toMap( query );
if ( removeCredentials ) {
map.remove( "USER" );
map.remove( "PASSWORD" );
map.remove( "SESSIONID" );
query = "";
for ( String key : map.keySet() ) {
query += key + "=" + map.get( key ) + "&";
}
query = query.substring( 0, query.length() - 1 );
}
String service = getService( map );
String hostAddr = host.get( service );
String req = hostAddr + "?" + query;
URL url = new URL( req );
LOG.logDebug( "forward URL: " + url );
URLConnection con = url.openConnection();
con.setDoInput( true );
con.setDoOutput( false );
is = con.getInputStream();
response.setContentType( con.getContentType() );
response.setCharacterEncoding( con.getContentEncoding() );
os = response.getOutputStream();
int read = 0;
byte[] buf = new byte[16384];
if ( LOG.getLevel() == ILogger.LOG_DEBUG ) {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
LOG.logDebug( new String( buf, 0, read, con.getContentEncoding() == null ? "UTF-8"
: con.getContentEncoding() ) );
}
} else {
while ( ( read = is.read( buf ) ) > -1 ) {
os.write( buf, 0, read );
}
}
} catch ( Exception e ) {
e.printStackTrace();
response.setContentType( "text/plain; charset=" + CharsetUtils.getSystemCharset() );
os.write( StringTools.stackTraceToString( e ).getBytes() );
} finally {
try {
is.close();
} catch ( Exception e ) {
// try to do what ?
}
try {
os.close();
} catch ( Exception e ) {
// try to do what ?
}
}
}
|
diff --git a/src/loop/LoopShell.java b/src/loop/LoopShell.java
index 5b0dca8..c42818f 100644
--- a/src/loop/LoopShell.java
+++ b/src/loop/LoopShell.java
@@ -1,398 +1,399 @@
package loop;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import jline.console.completer.FileNameCompleter;
import loop.ast.Assignment;
import loop.ast.Node;
import loop.ast.Variable;
import loop.ast.script.FunctionDecl;
import loop.ast.script.ModuleDecl;
import loop.ast.script.ModuleLoader;
import loop.ast.script.RequireDecl;
import loop.ast.script.Unit;
import loop.lang.LoopObject;
import loop.runtime.Closure;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author [email protected] (Dhanji R. Prasanna)
*/
public class LoopShell {
private static Map<String, Object> shellContext;
public static Object shellObtain(String var) {
return shellContext.get(var);
}
public static void shell() {
System.out.println("loOp (http://looplang.org)");
System.out.println(" by Dhanji R. Prasanna\n");
try {
ConsoleReader reader = new ConsoleReader();
+ reader.setExpandEvents(false);
reader.addCompleter(new MetaCommandCompleter());
Unit shellScope = new Unit(null, ModuleDecl.SHELL);
FunctionDecl main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
boolean inFunction = false;
// Used to build up multiline statement blocks (like functions)
StringBuilder block = null;
//noinspection InfiniteLoopStatement
do {
String prompt = (block != null) ? "| " : ">> ";
String rawLine = reader.readLine(prompt);
if (inFunction) {
if (rawLine == null || rawLine.trim().isEmpty()) {
inFunction = false;
// Eval the function to verify it.
printResult(Loop.evalClassOrFunction(block.toString(), shellScope));
block = null;
continue;
}
block.append(rawLine).append('\n');
continue;
}
if (rawLine == null) {
quit();
}
//noinspection ConstantConditions
String line = rawLine.trim();
if (line.isEmpty())
continue;
// Add a require import.
if (line.startsWith("require ")) {
shellScope.declare(new Parser(new Tokenizer(line + '\n').tokenize()).require());
shellScope.loadDeps("<shell>");
continue;
}
if (line.startsWith(":q") || line.startsWith(":quit")) {
quit();
}
if (line.startsWith(":h") || line.startsWith(":help")) {
printHelp();
}
if (line.startsWith(":run")) {
String[] split = line.split("[ ]+", 2);
if (split.length < 2 || !split[1].endsWith(".loop"))
System.out.println("You must specify a .loop file to run.");
Loop.run(split[1]);
continue;
}
if (line.startsWith(":r") || line.startsWith(":reset")) {
System.out.println("Context reset.");
shellScope = new Unit(null, ModuleDecl.SHELL);
main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
continue;
}
if (line.startsWith(":i") || line.startsWith(":imports")) {
for (RequireDecl requireDecl : shellScope.imports()) {
System.out.println(requireDecl.toSymbol());
}
System.out.println();
continue;
}
if (line.startsWith(":f") || line.startsWith(":functions")) {
for (FunctionDecl functionDecl : shellScope.functions()) {
StringBuilder args = new StringBuilder();
List<Node> children = functionDecl.arguments().children();
for (int i = 0, childrenSize = children.size(); i < childrenSize; i++) {
Node arg = children.get(i);
args.append(arg.toSymbol());
if (i < childrenSize - 1)
args.append(", ");
}
System.out.println(functionDecl.name()
+ ": (" + args.toString() + ")"
+ (functionDecl.patternMatching ? " #pattern-matching" : "")
);
}
System.out.println();
continue;
}
if (line.startsWith(":t") || line.startsWith(":type")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
printTypeOf(result);
continue;
}
if (line.startsWith(":javatype")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
if (result instanceof LoopError)
System.out.println(result.toString());
else
System.out.println(result == null ? "null" : result.getClass().getName());
continue;
}
// Function definitions can be multiline.
if (line.endsWith("->") || line.endsWith("=>")) {
inFunction = true;
block = new StringBuilder(line).append('\n');
continue;
} else if (isDangling(line)) {
if (block == null)
block = new StringBuilder();
block.append(line).append('\n');
continue;
}
if (block != null) {
rawLine = block.append(line).toString();
block = null;
}
// First determine what kind of expression this is.
main.children().clear();
// OK execute expression.
try {
printResult(evalInFunction(rawLine, main, shellScope, true));
} catch (ClassCastException e) {
StackTraceSanitizer.cleanForShell(e);
System.out.println("#error: " + e.getMessage());
System.out.println();
} catch (RuntimeException e) {
StackTraceSanitizer.cleanForShell(e);
e.printStackTrace();
System.out.println();
}
} while (true);
} catch (IOException e) {
System.err.println("Something went wrong =(");
System.exit(1);
}
}
private static void printHelp() {
System.out.println("loOp Shell v1.0");
System.out.println(" :run <file.loop> - executes the specified loop file");
System.out.println(" :reset - discards current shell context (variables, funcs, etc.)");
System.out.println(" :imports - lists all currently imported loop modules and Java types");
System.out.println(" :functions - lists all currently defined functions by signature");
System.out.println(" :type <expr> - prints the type of the given expression");
System.out.println(" :javatype <expr> - prints the underlying java type (for examining loop internals)");
System.out.println(" :quit (or Ctrl-D) - exits the loop shell");
System.out.println(" :help - prints this help card");
System.out.println();
System.out.println(" Hint :h is short for :help, etc.");
}
private static void printTypeOf(Object result) {
if (result instanceof LoopError)
System.out.println(result.toString());
else if (result instanceof LoopObject)
System.out.println(((LoopObject)result).getType());
else if (result instanceof Closure)
System.out.println("#function: " + ((Closure)result).name);
else
System.out.println(result == null ? "Nothing" : "#java: " + result.getClass().getName());
}
private static Object evalInFunction(String rawLine,
FunctionDecl func,
Unit shellScope,
boolean addToWhereBlock) {
rawLine = rawLine.trim() + '\n';
Executable executable = new Executable(new StringReader(rawLine));
Node parsedLine;
try {
Parser parser = new Parser(new Tokenizer(rawLine).tokenize(), shellScope);
parsedLine = parser.line();
if (parsedLine == null || !parser.getErrors().isEmpty()) {
executable.printErrors(parser.getErrors());
return "";
}
// If this is an assignment, just check the rhs portion of it.
// This is a bit hacky but prevents verification from balking about new
// vars declared in the lhs.
if (parsedLine instanceof Assignment) {
Assignment assignment = (Assignment) parsedLine;
func.children().add(assignment.rhs());
} else
func.children().add(parsedLine);
// Compress nodes and eliminate redundancies.
new Reducer(func).reduce();
shellScope.loadDeps("<shell>");
executable.runMain(true);
executable.compileExpression(shellScope);
if (executable.hasErrors()) {
executable.printStaticErrorsIfNecessary();
return "";
}
} catch (Exception e) {
e.printStackTrace();
return new LoopError("malformed expression " + rawLine);
}
try {
Object result = Loop.safeEval(executable, null);
if (addToWhereBlock && parsedLine instanceof Assignment) {
Assignment assignment = (Assignment) parsedLine;
new Reducer(assignment).reduce();
boolean shouldReplace = false;
if (assignment.lhs() instanceof Variable) {
String name = ((Variable) assignment.lhs()).name;
shellContext.put(name, result);
// Loop up the value of the RHS of the variable from the shell context,
// if this is the second reference to the same variable.
assignment.setRhs(new Parser(new Tokenizer(
"`loop.LoopShell`.shellObtain('" + name + "')").tokenize()).parse());
shouldReplace = true;
}
// If this assignment is already present in the current scope, we should replace it.
if (shouldReplace)
for (Iterator<Node> iterator = func.whereBlock().iterator(); iterator.hasNext(); ) {
Node node = iterator.next();
if (node instanceof Assignment && ((Assignment) node).lhs() instanceof Variable) {
iterator.remove();
}
}
func.declareLocally(parsedLine);
}
return result;
} finally {
ModuleLoader.reset(); // Cleans up the loaded classes.
}
}
private static void printResult(Object result) {
if (result instanceof Closure) {
Closure fun = (Closure) result;
System.out.println("#function: " + fun.name);
} else if (result instanceof Set) {
String r = result.toString();
System.out.println('{' + r.substring(1, r.length() - 1) + '}');
}
else
System.out.println(result == null ? "#nothing" : result);
}
private static boolean isLoadCommand(String line) {
return line.startsWith(":run");
}
private static void quit() {
System.out.println("Bye.");
System.exit(0);
}
// For tracking multiline expressions.
private static int braces = 0, brackets = 0, parens = 0;
private static boolean isDangling(String line) {
for (Token token : new Tokenizer(line).tokenize()) {
switch (token.kind) {
case LBRACE:
braces++;
break;
case LBRACKET:
brackets++;
break;
case LPAREN:
parens++;
break;
case RBRACE:
braces--;
break;
case RBRACKET:
brackets--;
break;
case RPAREN:
parens--;
break;
}
}
return braces > 0 || brackets > 0 || parens > 0;
}
private static class MetaCommandCompleter implements Completer {
private final List<String> commands = Arrays.asList(
":help",
":run",
":quit",
":reset",
":type",
":imports",
":javatype",
":functions"
);
private final FileNameCompleter fileNameCompleter = new FileNameCompleter();
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) {
if (buffer == null) {
buffer = "";
} else
buffer = buffer.trim();
// See if we should chain to the filename completer first.
if (isLoadCommand(buffer)) {
String[] split = buffer.split("[ ]+");
// Always complete the first argument.
if (split.length > 1)
return fileNameCompleter.complete(split[split.length - 1], cursor, candidates);
}
for (String command : commands) {
if (command.startsWith(buffer)) {
candidates.add(command.substring(buffer.length()) + ' ');
}
}
return cursor;
}
}
}
| true | true | public static void shell() {
System.out.println("loOp (http://looplang.org)");
System.out.println(" by Dhanji R. Prasanna\n");
try {
ConsoleReader reader = new ConsoleReader();
reader.addCompleter(new MetaCommandCompleter());
Unit shellScope = new Unit(null, ModuleDecl.SHELL);
FunctionDecl main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
boolean inFunction = false;
// Used to build up multiline statement blocks (like functions)
StringBuilder block = null;
//noinspection InfiniteLoopStatement
do {
String prompt = (block != null) ? "| " : ">> ";
String rawLine = reader.readLine(prompt);
if (inFunction) {
if (rawLine == null || rawLine.trim().isEmpty()) {
inFunction = false;
// Eval the function to verify it.
printResult(Loop.evalClassOrFunction(block.toString(), shellScope));
block = null;
continue;
}
block.append(rawLine).append('\n');
continue;
}
if (rawLine == null) {
quit();
}
//noinspection ConstantConditions
String line = rawLine.trim();
if (line.isEmpty())
continue;
// Add a require import.
if (line.startsWith("require ")) {
shellScope.declare(new Parser(new Tokenizer(line + '\n').tokenize()).require());
shellScope.loadDeps("<shell>");
continue;
}
if (line.startsWith(":q") || line.startsWith(":quit")) {
quit();
}
if (line.startsWith(":h") || line.startsWith(":help")) {
printHelp();
}
if (line.startsWith(":run")) {
String[] split = line.split("[ ]+", 2);
if (split.length < 2 || !split[1].endsWith(".loop"))
System.out.println("You must specify a .loop file to run.");
Loop.run(split[1]);
continue;
}
if (line.startsWith(":r") || line.startsWith(":reset")) {
System.out.println("Context reset.");
shellScope = new Unit(null, ModuleDecl.SHELL);
main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
continue;
}
if (line.startsWith(":i") || line.startsWith(":imports")) {
for (RequireDecl requireDecl : shellScope.imports()) {
System.out.println(requireDecl.toSymbol());
}
System.out.println();
continue;
}
if (line.startsWith(":f") || line.startsWith(":functions")) {
for (FunctionDecl functionDecl : shellScope.functions()) {
StringBuilder args = new StringBuilder();
List<Node> children = functionDecl.arguments().children();
for (int i = 0, childrenSize = children.size(); i < childrenSize; i++) {
Node arg = children.get(i);
args.append(arg.toSymbol());
if (i < childrenSize - 1)
args.append(", ");
}
System.out.println(functionDecl.name()
+ ": (" + args.toString() + ")"
+ (functionDecl.patternMatching ? " #pattern-matching" : "")
);
}
System.out.println();
continue;
}
if (line.startsWith(":t") || line.startsWith(":type")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
printTypeOf(result);
continue;
}
if (line.startsWith(":javatype")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
if (result instanceof LoopError)
System.out.println(result.toString());
else
System.out.println(result == null ? "null" : result.getClass().getName());
continue;
}
// Function definitions can be multiline.
if (line.endsWith("->") || line.endsWith("=>")) {
inFunction = true;
block = new StringBuilder(line).append('\n');
continue;
} else if (isDangling(line)) {
if (block == null)
block = new StringBuilder();
block.append(line).append('\n');
continue;
}
if (block != null) {
rawLine = block.append(line).toString();
block = null;
}
// First determine what kind of expression this is.
main.children().clear();
// OK execute expression.
try {
printResult(evalInFunction(rawLine, main, shellScope, true));
} catch (ClassCastException e) {
StackTraceSanitizer.cleanForShell(e);
System.out.println("#error: " + e.getMessage());
System.out.println();
} catch (RuntimeException e) {
StackTraceSanitizer.cleanForShell(e);
e.printStackTrace();
System.out.println();
}
} while (true);
} catch (IOException e) {
System.err.println("Something went wrong =(");
System.exit(1);
}
}
| public static void shell() {
System.out.println("loOp (http://looplang.org)");
System.out.println(" by Dhanji R. Prasanna\n");
try {
ConsoleReader reader = new ConsoleReader();
reader.setExpandEvents(false);
reader.addCompleter(new MetaCommandCompleter());
Unit shellScope = new Unit(null, ModuleDecl.SHELL);
FunctionDecl main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
boolean inFunction = false;
// Used to build up multiline statement blocks (like functions)
StringBuilder block = null;
//noinspection InfiniteLoopStatement
do {
String prompt = (block != null) ? "| " : ">> ";
String rawLine = reader.readLine(prompt);
if (inFunction) {
if (rawLine == null || rawLine.trim().isEmpty()) {
inFunction = false;
// Eval the function to verify it.
printResult(Loop.evalClassOrFunction(block.toString(), shellScope));
block = null;
continue;
}
block.append(rawLine).append('\n');
continue;
}
if (rawLine == null) {
quit();
}
//noinspection ConstantConditions
String line = rawLine.trim();
if (line.isEmpty())
continue;
// Add a require import.
if (line.startsWith("require ")) {
shellScope.declare(new Parser(new Tokenizer(line + '\n').tokenize()).require());
shellScope.loadDeps("<shell>");
continue;
}
if (line.startsWith(":q") || line.startsWith(":quit")) {
quit();
}
if (line.startsWith(":h") || line.startsWith(":help")) {
printHelp();
}
if (line.startsWith(":run")) {
String[] split = line.split("[ ]+", 2);
if (split.length < 2 || !split[1].endsWith(".loop"))
System.out.println("You must specify a .loop file to run.");
Loop.run(split[1]);
continue;
}
if (line.startsWith(":r") || line.startsWith(":reset")) {
System.out.println("Context reset.");
shellScope = new Unit(null, ModuleDecl.SHELL);
main = new FunctionDecl("main", null);
shellScope.declare(main);
shellContext = new HashMap<String, Object>();
continue;
}
if (line.startsWith(":i") || line.startsWith(":imports")) {
for (RequireDecl requireDecl : shellScope.imports()) {
System.out.println(requireDecl.toSymbol());
}
System.out.println();
continue;
}
if (line.startsWith(":f") || line.startsWith(":functions")) {
for (FunctionDecl functionDecl : shellScope.functions()) {
StringBuilder args = new StringBuilder();
List<Node> children = functionDecl.arguments().children();
for (int i = 0, childrenSize = children.size(); i < childrenSize; i++) {
Node arg = children.get(i);
args.append(arg.toSymbol());
if (i < childrenSize - 1)
args.append(", ");
}
System.out.println(functionDecl.name()
+ ": (" + args.toString() + ")"
+ (functionDecl.patternMatching ? " #pattern-matching" : "")
);
}
System.out.println();
continue;
}
if (line.startsWith(":t") || line.startsWith(":type")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
printTypeOf(result);
continue;
}
if (line.startsWith(":javatype")) {
String[] split = line.split("[ ]+", 2);
if (split.length <= 1) {
System.out.println("Give me an expression to determine the type for.\n");
continue;
}
Object result = evalInFunction(split[1], main, shellScope, false);
if (result instanceof LoopError)
System.out.println(result.toString());
else
System.out.println(result == null ? "null" : result.getClass().getName());
continue;
}
// Function definitions can be multiline.
if (line.endsWith("->") || line.endsWith("=>")) {
inFunction = true;
block = new StringBuilder(line).append('\n');
continue;
} else if (isDangling(line)) {
if (block == null)
block = new StringBuilder();
block.append(line).append('\n');
continue;
}
if (block != null) {
rawLine = block.append(line).toString();
block = null;
}
// First determine what kind of expression this is.
main.children().clear();
// OK execute expression.
try {
printResult(evalInFunction(rawLine, main, shellScope, true));
} catch (ClassCastException e) {
StackTraceSanitizer.cleanForShell(e);
System.out.println("#error: " + e.getMessage());
System.out.println();
} catch (RuntimeException e) {
StackTraceSanitizer.cleanForShell(e);
e.printStackTrace();
System.out.println();
}
} while (true);
} catch (IOException e) {
System.err.println("Something went wrong =(");
System.exit(1);
}
}
|
diff --git a/WiFiServer/src/org/openintents/wifiserver/requesthandler/FileHandler.java b/WiFiServer/src/org/openintents/wifiserver/requesthandler/FileHandler.java
index 6442123..73745be 100644
--- a/WiFiServer/src/org/openintents/wifiserver/requesthandler/FileHandler.java
+++ b/WiFiServer/src/org/openintents/wifiserver/requesthandler/FileHandler.java
@@ -1,112 +1,112 @@
package org.openintents.wifiserver.requesthandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.openintents.wifiserver.preference.OiWiFiPreferences_;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
@EBean
public class FileHandler implements HttpRequestHandler {
private final static String TAG = FileHandler.class.getSimpleName();
@RootContext protected Context mContext;
@Pref protected OiWiFiPreferences_ prefs;
private final static Map<String, String> mimeMapping = new HashMap<String, String>() {
private static final long serialVersionUID = -439543272217048417L;
{
put("js", "text/javascript");
put("htm", "text/html");
put("html", "text/html");
put("png", "image/png");
put("css", "text/css");
put("gif", "image/gif");
}
};
@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext context) throws HttpException, IOException {
String path = Uri.parse(request.getRequestLine().getUri()).getPath();
AbstractHttpEntity entity;
if ("/".equals(path)) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri()+"index.html");
return;
}
if ("/index.html".equals(path)) {
Object authAttribute = context.getAttribute("authenticated");
if (!(authAttribute == null || (authAttribute instanceof Boolean && ((Boolean) authAttribute).booleanValue()))) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri().replace("index.html","login.html"));
return;
}
}
if ("/login.html".equals(path)){
- final InputStream input = mContext.getAssets().open("WebInterface"+path);
+ final InputStream input = mContext.getAssets().open("webinterface"+path);
String password = prefs.customPassword().get();
String salt = password.substring(password.length()-8);
StringBuilder result = new StringBuilder();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (null != (line=reader.readLine())) {
result.append(line.replace("$SALT$", salt));
result.append('\n');
}
entity = new StringEntity(result.toString());
entity.setContentType("text/html");
response.setEntity(entity);
response.setStatusCode(200);
return;
}
try {
- InputStream input = mContext.getAssets().open("WebInterface"+path);
+ InputStream input = mContext.getAssets().open("webinterface"+path);
entity = new InputStreamEntity(input, -1);
response.setEntity(entity);
String ending = path.substring(path.lastIndexOf(".")+1);
if (ending != null && ending.length() > 0) {
String mime = mimeMapping.get(ending);
if (mime != null) {
entity.setContentType(mime);
}
}
response.setStatusCode(200);
return;
} catch (IOException e) {
Log.e(TAG, e.getMessage());
entity = new StringEntity("404 Not Found");
entity.setContentType("text/plain");
response.setEntity(entity);
response.setStatusCode(404);
}
}
}
| false | true | public void handle(final HttpRequest request, final HttpResponse response, HttpContext context) throws HttpException, IOException {
String path = Uri.parse(request.getRequestLine().getUri()).getPath();
AbstractHttpEntity entity;
if ("/".equals(path)) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri()+"index.html");
return;
}
if ("/index.html".equals(path)) {
Object authAttribute = context.getAttribute("authenticated");
if (!(authAttribute == null || (authAttribute instanceof Boolean && ((Boolean) authAttribute).booleanValue()))) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri().replace("index.html","login.html"));
return;
}
}
if ("/login.html".equals(path)){
final InputStream input = mContext.getAssets().open("WebInterface"+path);
String password = prefs.customPassword().get();
String salt = password.substring(password.length()-8);
StringBuilder result = new StringBuilder();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (null != (line=reader.readLine())) {
result.append(line.replace("$SALT$", salt));
result.append('\n');
}
entity = new StringEntity(result.toString());
entity.setContentType("text/html");
response.setEntity(entity);
response.setStatusCode(200);
return;
}
try {
InputStream input = mContext.getAssets().open("WebInterface"+path);
entity = new InputStreamEntity(input, -1);
response.setEntity(entity);
String ending = path.substring(path.lastIndexOf(".")+1);
if (ending != null && ending.length() > 0) {
String mime = mimeMapping.get(ending);
if (mime != null) {
entity.setContentType(mime);
}
}
response.setStatusCode(200);
return;
} catch (IOException e) {
Log.e(TAG, e.getMessage());
entity = new StringEntity("404 Not Found");
entity.setContentType("text/plain");
response.setEntity(entity);
response.setStatusCode(404);
}
}
| public void handle(final HttpRequest request, final HttpResponse response, HttpContext context) throws HttpException, IOException {
String path = Uri.parse(request.getRequestLine().getUri()).getPath();
AbstractHttpEntity entity;
if ("/".equals(path)) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri()+"index.html");
return;
}
if ("/index.html".equals(path)) {
Object authAttribute = context.getAttribute("authenticated");
if (!(authAttribute == null || (authAttribute instanceof Boolean && ((Boolean) authAttribute).booleanValue()))) {
response.setStatusCode(301);
response.setHeader("Location", request.getRequestLine().getUri().replace("index.html","login.html"));
return;
}
}
if ("/login.html".equals(path)){
final InputStream input = mContext.getAssets().open("webinterface"+path);
String password = prefs.customPassword().get();
String salt = password.substring(password.length()-8);
StringBuilder result = new StringBuilder();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (null != (line=reader.readLine())) {
result.append(line.replace("$SALT$", salt));
result.append('\n');
}
entity = new StringEntity(result.toString());
entity.setContentType("text/html");
response.setEntity(entity);
response.setStatusCode(200);
return;
}
try {
InputStream input = mContext.getAssets().open("webinterface"+path);
entity = new InputStreamEntity(input, -1);
response.setEntity(entity);
String ending = path.substring(path.lastIndexOf(".")+1);
if (ending != null && ending.length() > 0) {
String mime = mimeMapping.get(ending);
if (mime != null) {
entity.setContentType(mime);
}
}
response.setStatusCode(200);
return;
} catch (IOException e) {
Log.e(TAG, e.getMessage());
entity = new StringEntity("404 Not Found");
entity.setContentType("text/plain");
response.setEntity(entity);
response.setStatusCode(404);
}
}
|
diff --git a/src/main/java/org/mozilla/gecko/background/fxa/FxAccount20CreateDelegate.java b/src/main/java/org/mozilla/gecko/background/fxa/FxAccount20CreateDelegate.java
index 6681c03be..e9f7556cf 100644
--- a/src/main/java/org/mozilla/gecko/background/fxa/FxAccount20CreateDelegate.java
+++ b/src/main/java/org/mozilla/gecko/background/fxa/FxAccount20CreateDelegate.java
@@ -1,51 +1,55 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.background.fxa;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import org.json.simple.JSONObject;
import org.mozilla.gecko.background.fxa.FxAccountClient10.CreateDelegate;
import org.mozilla.gecko.sync.Utils;
public class FxAccount20CreateDelegate implements CreateDelegate {
protected final byte[] emailUTF8;
protected final byte[] authPW;
protected final boolean preVerified;
/**
* Make a new "create account" delegate.
*
* @param emailUTF8
* email as UTF-8 bytes.
* @param quickStretchedPW
* quick stretched password as bytes.
* @param preVerified
* true if account should be marked already verified; only effective
* for non-production auth servers.
* @throws UnsupportedEncodingException
* @throws GeneralSecurityException
*/
public FxAccount20CreateDelegate(byte[] emailUTF8, byte[] quickStretchedPW, boolean preVerified) throws UnsupportedEncodingException, GeneralSecurityException {
this.emailUTF8 = emailUTF8;
this.authPW = FxAccountUtils.generateAuthPW(quickStretchedPW);
this.preVerified = preVerified;
}
@SuppressWarnings("unchecked")
@Override
public JSONObject getCreateBody() throws FxAccountClientException {
final JSONObject body = new JSONObject();
try {
body.put("email", new String(emailUTF8, "UTF-8"));
body.put("authPW", Utils.byte2Hex(authPW));
- body.put("preVerified", preVerified);
+ if (preVerified) {
+ // Production endpoints do not allow preVerified; this assumes we only
+ // set it when it's okay to send it.
+ body.put("preVerified", preVerified);
+ }
return body;
} catch (UnsupportedEncodingException e) {
throw new FxAccountClientException(e);
}
}
}
| true | true | public JSONObject getCreateBody() throws FxAccountClientException {
final JSONObject body = new JSONObject();
try {
body.put("email", new String(emailUTF8, "UTF-8"));
body.put("authPW", Utils.byte2Hex(authPW));
body.put("preVerified", preVerified);
return body;
} catch (UnsupportedEncodingException e) {
throw new FxAccountClientException(e);
}
}
| public JSONObject getCreateBody() throws FxAccountClientException {
final JSONObject body = new JSONObject();
try {
body.put("email", new String(emailUTF8, "UTF-8"));
body.put("authPW", Utils.byte2Hex(authPW));
if (preVerified) {
// Production endpoints do not allow preVerified; this assumes we only
// set it when it's okay to send it.
body.put("preVerified", preVerified);
}
return body;
} catch (UnsupportedEncodingException e) {
throw new FxAccountClientException(e);
}
}
|
diff --git a/src/commons/org/codehaus/groovy/grails/cli/support/GrailsStarter.java b/src/commons/org/codehaus/groovy/grails/cli/support/GrailsStarter.java
index ea04944c9..2d270bdcf 100644
--- a/src/commons/org/codehaus/groovy/grails/cli/support/GrailsStarter.java
+++ b/src/commons/org/codehaus/groovy/grails/cli/support/GrailsStarter.java
@@ -1,254 +1,254 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.cli.support;
import org.codehaus.groovy.tools.LoaderConfiguration;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;
import java.util.regex.Pattern;
/**
* @author Graeme Rocher
* @since 1.0
* <p/>
* Created: Nov 29, 2007
*/
public class GrailsStarter {
static void printUsage() {
System.out.println("possible programs are 'groovyc','groovy','console', and 'groovysh'");
System.exit(1);
}
public static void rootLoader(String args[]) {
final String separator = System.getProperty("file.separator");
// Set some default values for various system properties if
// they don't already have values.
String javaVersion = System.getProperty("java.version");
String grailsHome = System.getProperty("grails.home");
if (System.getProperty("base.dir") == null) System.setProperty("base.dir", ".");
if (System.getProperty("program.name") == null) System.setProperty("program.name", "grails");
if (System.getProperty("groovy.starter.conf") == null) {
System.setProperty(
"groovy.starter.conf",
grailsHome + separator + "conf" + separator + "groovy-starter.conf");
}
// Initialise the Grails version if it's not set already.
if (System.getProperty("grails.version") == null) {
Properties grailsProps = new Properties();
FileInputStream is = null;
try {
// Load Grails' "build.properties" file.
is = new FileInputStream(grailsHome + separator + "build.properties");
grailsProps.load(is);
// Extract the Grails version and store as a system
// property so that it can be referenced from the
// starter configuration file.
System.setProperty("grails.version", grailsProps.getProperty("grails.version"));
}
catch (IOException ex) { System.out.println("Failed to load Grails file: " + ex.getMessage()); System.exit(1); }
finally { if (is != null) try { is.close(); } catch (IOException ex2) {} }
}
String conf = System.getProperty("groovy.starter.conf", null);
LoaderConfiguration lc = new LoaderConfiguration();
// evaluate parameters
boolean hadMain=false, hadConf=false, hadCP=false;
int argsOffset = 0;
while (args.length-argsOffset>0 && !(hadMain && hadConf && hadCP)) {
if (args[argsOffset].equals("--classpath")) {
if (hadCP) break;
if (args.length==argsOffset+1) {
exit("classpath parameter needs argument");
}
lc.addClassPath(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--main")) {
if (hadMain) break;
if (args.length==argsOffset+1) {
exit("main parameter needs argument");
}
lc.setMainClass(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--conf")) {
if (hadConf) break;
if (args.length==argsOffset+1) {
exit("conf parameter needs argument");
}
conf=args[argsOffset+1];
argsOffset+=2;
} else {
break;
}
}
// We need to know the class we want to start
- if (lc.getMainClass()==null && conf==null) {
+ if (lc.getMainClass()==null) {
lc.setMainClass("org.codehaus.groovy.grails.cli.GrailsScriptRunner");
}
// copy arguments for main class
String[] newArgs = new String[args.length-argsOffset];
for (int i=0; i<newArgs.length; i++) {
newArgs[i] = args[i+argsOffset];
}
// load configuration file
if (conf!=null) {
try {
lc.configure(new FileInputStream(conf));
} catch (Exception e) {
System.err.println("exception while configuring main class loader:");
exit(e);
}
}
// obtain servlet version
String servletVersion = "2.4";
Pattern standardJarPattern = Pattern.compile(".+?standard-\\d\\.\\d\\.jar");
Pattern jstlJarPattern = Pattern.compile(".+?jstl-\\d\\.\\d\\.jar");
Properties metadata = new Properties();
File metadataFile = new File("./application.properties");
if(metadataFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(metadataFile);
metadata.load(inputStream);
Object version = metadata.get("app.servlet.version");
if(version!=null) {
servletVersion = version.toString();
}
} catch (IOException e) {
// ignore
}
finally {
try {
if(inputStream!=null) inputStream.close();
} catch (IOException e) {
// ignore
}
}
}
// create loader and execute main class
GrailsRootLoader loader = new GrailsRootLoader();
Thread.currentThread().setContextClassLoader(loader);
final String standardJarName = "standard-" + servletVersion + ".jar";
final String jstlJarName = "jstl-" + servletVersion + ".jar";
// configure class loader
URL[] urls = lc.getClassPathUrls();
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
final String path = url.getPath();
if(standardJarPattern.matcher(path).find()) {
if(path.endsWith(standardJarName)) {
loader.addURL(url);
}
}
else if(jstlJarPattern.matcher(path).find()) {
if(path.endsWith(jstlJarName)) {
loader.addURL(url);
}
}
else {
loader.addURL(url);
}
}
if(javaVersion != null && grailsHome != null) {
javaVersion = javaVersion.substring(0,3);
File vmConfig = new File(grailsHome +"/conf/groovy-starter-java-"+javaVersion+".conf");
if(vmConfig.exists()) {
InputStream in = null;
try {
in = new FileInputStream(vmConfig);
LoaderConfiguration vmLoaderConfig = new LoaderConfiguration();
vmLoaderConfig.setRequireMain(false);
vmLoaderConfig.configure(in);
URL[] vmSpecificClassPath = vmLoaderConfig.getClassPathUrls();
for (int i = 0; i < vmSpecificClassPath.length; i++) {
loader.addURL(vmSpecificClassPath[i]);
}
} catch (IOException e) {
System.out.println("WARNING: I/O error reading VM specific classpath ["+vmConfig+"]: " + e.getMessage() );
}
finally {
try {
if(in != null) in.close();
} catch (IOException e) {
// ignore
}
}
}
}
Method m=null;
try {
Class c = loader.loadClass(lc.getMainClass());
m = c.getMethod("main", new Class[]{String[].class});
} catch (ClassNotFoundException e1) {
exit(e1);
} catch (SecurityException e2) {
exit(e2);
} catch (NoSuchMethodException e2) {
exit(e2);
}
try {
m.invoke(null, new Object[]{newArgs});
} catch (IllegalArgumentException e3) {
exit(e3);
} catch (IllegalAccessException e3) {
exit(e3);
} catch (InvocationTargetException e3) {
exit(e3);
}
}
private static void exit(Exception e) {
e.printStackTrace();
System.exit(1);
}
private static void exit(String msg) {
System.err.println(msg);
System.exit(1);
}
// after migration from classworlds to the rootloader rename
// the rootLoader method to main and remove this method as
// well as the classworlds method
public static void main(String args[]) {
try {
rootLoader(args);
} catch (Throwable t) {
System.out.println("Error starting Grails: " + t.getMessage());
t.printStackTrace(System.err);
System.exit(1);
}
}
}
| true | true | public static void rootLoader(String args[]) {
final String separator = System.getProperty("file.separator");
// Set some default values for various system properties if
// they don't already have values.
String javaVersion = System.getProperty("java.version");
String grailsHome = System.getProperty("grails.home");
if (System.getProperty("base.dir") == null) System.setProperty("base.dir", ".");
if (System.getProperty("program.name") == null) System.setProperty("program.name", "grails");
if (System.getProperty("groovy.starter.conf") == null) {
System.setProperty(
"groovy.starter.conf",
grailsHome + separator + "conf" + separator + "groovy-starter.conf");
}
// Initialise the Grails version if it's not set already.
if (System.getProperty("grails.version") == null) {
Properties grailsProps = new Properties();
FileInputStream is = null;
try {
// Load Grails' "build.properties" file.
is = new FileInputStream(grailsHome + separator + "build.properties");
grailsProps.load(is);
// Extract the Grails version and store as a system
// property so that it can be referenced from the
// starter configuration file.
System.setProperty("grails.version", grailsProps.getProperty("grails.version"));
}
catch (IOException ex) { System.out.println("Failed to load Grails file: " + ex.getMessage()); System.exit(1); }
finally { if (is != null) try { is.close(); } catch (IOException ex2) {} }
}
String conf = System.getProperty("groovy.starter.conf", null);
LoaderConfiguration lc = new LoaderConfiguration();
// evaluate parameters
boolean hadMain=false, hadConf=false, hadCP=false;
int argsOffset = 0;
while (args.length-argsOffset>0 && !(hadMain && hadConf && hadCP)) {
if (args[argsOffset].equals("--classpath")) {
if (hadCP) break;
if (args.length==argsOffset+1) {
exit("classpath parameter needs argument");
}
lc.addClassPath(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--main")) {
if (hadMain) break;
if (args.length==argsOffset+1) {
exit("main parameter needs argument");
}
lc.setMainClass(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--conf")) {
if (hadConf) break;
if (args.length==argsOffset+1) {
exit("conf parameter needs argument");
}
conf=args[argsOffset+1];
argsOffset+=2;
} else {
break;
}
}
// We need to know the class we want to start
if (lc.getMainClass()==null && conf==null) {
lc.setMainClass("org.codehaus.groovy.grails.cli.GrailsScriptRunner");
}
// copy arguments for main class
String[] newArgs = new String[args.length-argsOffset];
for (int i=0; i<newArgs.length; i++) {
newArgs[i] = args[i+argsOffset];
}
// load configuration file
if (conf!=null) {
try {
lc.configure(new FileInputStream(conf));
} catch (Exception e) {
System.err.println("exception while configuring main class loader:");
exit(e);
}
}
// obtain servlet version
String servletVersion = "2.4";
Pattern standardJarPattern = Pattern.compile(".+?standard-\\d\\.\\d\\.jar");
Pattern jstlJarPattern = Pattern.compile(".+?jstl-\\d\\.\\d\\.jar");
Properties metadata = new Properties();
File metadataFile = new File("./application.properties");
if(metadataFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(metadataFile);
metadata.load(inputStream);
Object version = metadata.get("app.servlet.version");
if(version!=null) {
servletVersion = version.toString();
}
} catch (IOException e) {
// ignore
}
finally {
try {
if(inputStream!=null) inputStream.close();
} catch (IOException e) {
// ignore
}
}
}
// create loader and execute main class
GrailsRootLoader loader = new GrailsRootLoader();
Thread.currentThread().setContextClassLoader(loader);
final String standardJarName = "standard-" + servletVersion + ".jar";
final String jstlJarName = "jstl-" + servletVersion + ".jar";
// configure class loader
URL[] urls = lc.getClassPathUrls();
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
final String path = url.getPath();
if(standardJarPattern.matcher(path).find()) {
if(path.endsWith(standardJarName)) {
loader.addURL(url);
}
}
else if(jstlJarPattern.matcher(path).find()) {
if(path.endsWith(jstlJarName)) {
loader.addURL(url);
}
}
else {
loader.addURL(url);
}
}
if(javaVersion != null && grailsHome != null) {
javaVersion = javaVersion.substring(0,3);
File vmConfig = new File(grailsHome +"/conf/groovy-starter-java-"+javaVersion+".conf");
if(vmConfig.exists()) {
InputStream in = null;
try {
in = new FileInputStream(vmConfig);
LoaderConfiguration vmLoaderConfig = new LoaderConfiguration();
vmLoaderConfig.setRequireMain(false);
vmLoaderConfig.configure(in);
URL[] vmSpecificClassPath = vmLoaderConfig.getClassPathUrls();
for (int i = 0; i < vmSpecificClassPath.length; i++) {
loader.addURL(vmSpecificClassPath[i]);
}
} catch (IOException e) {
System.out.println("WARNING: I/O error reading VM specific classpath ["+vmConfig+"]: " + e.getMessage() );
}
finally {
try {
if(in != null) in.close();
} catch (IOException e) {
// ignore
}
}
}
}
Method m=null;
try {
Class c = loader.loadClass(lc.getMainClass());
m = c.getMethod("main", new Class[]{String[].class});
} catch (ClassNotFoundException e1) {
exit(e1);
} catch (SecurityException e2) {
exit(e2);
} catch (NoSuchMethodException e2) {
exit(e2);
}
try {
m.invoke(null, new Object[]{newArgs});
} catch (IllegalArgumentException e3) {
exit(e3);
} catch (IllegalAccessException e3) {
exit(e3);
} catch (InvocationTargetException e3) {
exit(e3);
}
}
| public static void rootLoader(String args[]) {
final String separator = System.getProperty("file.separator");
// Set some default values for various system properties if
// they don't already have values.
String javaVersion = System.getProperty("java.version");
String grailsHome = System.getProperty("grails.home");
if (System.getProperty("base.dir") == null) System.setProperty("base.dir", ".");
if (System.getProperty("program.name") == null) System.setProperty("program.name", "grails");
if (System.getProperty("groovy.starter.conf") == null) {
System.setProperty(
"groovy.starter.conf",
grailsHome + separator + "conf" + separator + "groovy-starter.conf");
}
// Initialise the Grails version if it's not set already.
if (System.getProperty("grails.version") == null) {
Properties grailsProps = new Properties();
FileInputStream is = null;
try {
// Load Grails' "build.properties" file.
is = new FileInputStream(grailsHome + separator + "build.properties");
grailsProps.load(is);
// Extract the Grails version and store as a system
// property so that it can be referenced from the
// starter configuration file.
System.setProperty("grails.version", grailsProps.getProperty("grails.version"));
}
catch (IOException ex) { System.out.println("Failed to load Grails file: " + ex.getMessage()); System.exit(1); }
finally { if (is != null) try { is.close(); } catch (IOException ex2) {} }
}
String conf = System.getProperty("groovy.starter.conf", null);
LoaderConfiguration lc = new LoaderConfiguration();
// evaluate parameters
boolean hadMain=false, hadConf=false, hadCP=false;
int argsOffset = 0;
while (args.length-argsOffset>0 && !(hadMain && hadConf && hadCP)) {
if (args[argsOffset].equals("--classpath")) {
if (hadCP) break;
if (args.length==argsOffset+1) {
exit("classpath parameter needs argument");
}
lc.addClassPath(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--main")) {
if (hadMain) break;
if (args.length==argsOffset+1) {
exit("main parameter needs argument");
}
lc.setMainClass(args[argsOffset+1]);
argsOffset+=2;
} else if (args[argsOffset].equals("--conf")) {
if (hadConf) break;
if (args.length==argsOffset+1) {
exit("conf parameter needs argument");
}
conf=args[argsOffset+1];
argsOffset+=2;
} else {
break;
}
}
// We need to know the class we want to start
if (lc.getMainClass()==null) {
lc.setMainClass("org.codehaus.groovy.grails.cli.GrailsScriptRunner");
}
// copy arguments for main class
String[] newArgs = new String[args.length-argsOffset];
for (int i=0; i<newArgs.length; i++) {
newArgs[i] = args[i+argsOffset];
}
// load configuration file
if (conf!=null) {
try {
lc.configure(new FileInputStream(conf));
} catch (Exception e) {
System.err.println("exception while configuring main class loader:");
exit(e);
}
}
// obtain servlet version
String servletVersion = "2.4";
Pattern standardJarPattern = Pattern.compile(".+?standard-\\d\\.\\d\\.jar");
Pattern jstlJarPattern = Pattern.compile(".+?jstl-\\d\\.\\d\\.jar");
Properties metadata = new Properties();
File metadataFile = new File("./application.properties");
if(metadataFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(metadataFile);
metadata.load(inputStream);
Object version = metadata.get("app.servlet.version");
if(version!=null) {
servletVersion = version.toString();
}
} catch (IOException e) {
// ignore
}
finally {
try {
if(inputStream!=null) inputStream.close();
} catch (IOException e) {
// ignore
}
}
}
// create loader and execute main class
GrailsRootLoader loader = new GrailsRootLoader();
Thread.currentThread().setContextClassLoader(loader);
final String standardJarName = "standard-" + servletVersion + ".jar";
final String jstlJarName = "jstl-" + servletVersion + ".jar";
// configure class loader
URL[] urls = lc.getClassPathUrls();
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
final String path = url.getPath();
if(standardJarPattern.matcher(path).find()) {
if(path.endsWith(standardJarName)) {
loader.addURL(url);
}
}
else if(jstlJarPattern.matcher(path).find()) {
if(path.endsWith(jstlJarName)) {
loader.addURL(url);
}
}
else {
loader.addURL(url);
}
}
if(javaVersion != null && grailsHome != null) {
javaVersion = javaVersion.substring(0,3);
File vmConfig = new File(grailsHome +"/conf/groovy-starter-java-"+javaVersion+".conf");
if(vmConfig.exists()) {
InputStream in = null;
try {
in = new FileInputStream(vmConfig);
LoaderConfiguration vmLoaderConfig = new LoaderConfiguration();
vmLoaderConfig.setRequireMain(false);
vmLoaderConfig.configure(in);
URL[] vmSpecificClassPath = vmLoaderConfig.getClassPathUrls();
for (int i = 0; i < vmSpecificClassPath.length; i++) {
loader.addURL(vmSpecificClassPath[i]);
}
} catch (IOException e) {
System.out.println("WARNING: I/O error reading VM specific classpath ["+vmConfig+"]: " + e.getMessage() );
}
finally {
try {
if(in != null) in.close();
} catch (IOException e) {
// ignore
}
}
}
}
Method m=null;
try {
Class c = loader.loadClass(lc.getMainClass());
m = c.getMethod("main", new Class[]{String[].class});
} catch (ClassNotFoundException e1) {
exit(e1);
} catch (SecurityException e2) {
exit(e2);
} catch (NoSuchMethodException e2) {
exit(e2);
}
try {
m.invoke(null, new Object[]{newArgs});
} catch (IllegalArgumentException e3) {
exit(e3);
} catch (IllegalAccessException e3) {
exit(e3);
} catch (InvocationTargetException e3) {
exit(e3);
}
}
|
diff --git a/uk.ac.diamond.scisoft.analysis/test/uk/ac/diamond/scisoft/analysis/dataset/LazyDatasetTest.java b/uk.ac.diamond.scisoft.analysis/test/uk/ac/diamond/scisoft/analysis/dataset/LazyDatasetTest.java
index 018dc9396..972262d25 100644
--- a/uk.ac.diamond.scisoft.analysis/test/uk/ac/diamond/scisoft/analysis/dataset/LazyDatasetTest.java
+++ b/uk.ac.diamond.scisoft.analysis/test/uk/ac/diamond/scisoft/analysis/dataset/LazyDatasetTest.java
@@ -1,108 +1,108 @@
/*-
* Copyright 2012 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.dataset;
import gda.analysis.io.ScanFileHolderException;
import org.junit.Assert;
import org.junit.Test;
import uk.ac.diamond.scisoft.analysis.io.ILazyLoader;
import uk.ac.diamond.scisoft.analysis.monitor.IMonitor;
public class LazyDatasetTest {
private void setShape(String msg, boolean well, LazyDataset l, int... shape) {
try {
l.setShape(shape);
if (well)
System.out.println("Succeeded setting shape for " + msg);
else
Assert.fail("Should have thrown exception for " + msg);
} catch (IllegalArgumentException iae) {
// do nothing
if (well)
Assert.fail("Unexpected exception for " + msg);
else
System.out.println("Correctly failed setting shape for " + msg);
} catch (Exception e) {
if (well)
Assert.fail("Unexpected exception for " + msg);
else
Assert.fail("Thrown wrong exception for " + msg);
}
}
@Test
public void testSetShape() {
LazyDataset ld = new LazyDataset("", AbstractDataset.INT, new int[] {1, 2, 3, 4}, null);
setShape("check on same rank", true, ld, 1, 2, 3, 4);
setShape("check on same rank", false, ld, 1, 2, 3, 5);
setShape("check on greater rank", true, ld, 1, 1, 1, 2, 3, 4);
setShape("check on greater rank", false, ld, 1, 2, 2, 3, 5);
setShape("check on greater rank", false, ld, 2, 1, 2, 3, 4);
setShape("check on lesser rank", true, ld, 2, 3, 4);
setShape("check on lesser rank", false, ld, 3, 4);
setShape("check on lesser rank", false, ld, 2, 3);
}
@Test
public void testGetSlice() {
final AbstractDataset d = Random.randn(new int[] {1, 2, 3, 4});
LazyDataset ld = new LazyDataset("", AbstractDataset.INT, new int[] {1, 2, 3, 4}, new ILazyLoader() {
@Override
public boolean isFileReadable() {
return true;
}
@Override
public AbstractDataset getDataset(IMonitor mon, int[] shape, int[] start, int[] stop, int[] step)
- throws ScanFileHolderException {
+ throws Exception {
return d.getSlice(mon, start, stop, step);
}
});
Slice[] slice;
slice = new Slice[]{null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", d, ld.getSlice());
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null));
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], new int[] { 1, 2, 3, 4 }, new int[] { 1, 1, 1, 1 }));
Assert.assertEquals("Part slice", d.getSlice(slice), ld.getSlice(slice));
AbstractDataset nd;
ld.setShape(1, 1, 1, 2, 3, 4);
nd = d.getView();
nd.setShape(1, 1, 1, 2, 3, 4);
slice = new Slice[]{null, null, null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
ld.setShape(2, 3, 4);
nd = d.getView();
nd.setShape(2, 3, 4);
slice = new Slice[]{new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
}
}
| true | true | public void testGetSlice() {
final AbstractDataset d = Random.randn(new int[] {1, 2, 3, 4});
LazyDataset ld = new LazyDataset("", AbstractDataset.INT, new int[] {1, 2, 3, 4}, new ILazyLoader() {
@Override
public boolean isFileReadable() {
return true;
}
@Override
public AbstractDataset getDataset(IMonitor mon, int[] shape, int[] start, int[] stop, int[] step)
throws ScanFileHolderException {
return d.getSlice(mon, start, stop, step);
}
});
Slice[] slice;
slice = new Slice[]{null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", d, ld.getSlice());
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null));
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], new int[] { 1, 2, 3, 4 }, new int[] { 1, 1, 1, 1 }));
Assert.assertEquals("Part slice", d.getSlice(slice), ld.getSlice(slice));
AbstractDataset nd;
ld.setShape(1, 1, 1, 2, 3, 4);
nd = d.getView();
nd.setShape(1, 1, 1, 2, 3, 4);
slice = new Slice[]{null, null, null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
ld.setShape(2, 3, 4);
nd = d.getView();
nd.setShape(2, 3, 4);
slice = new Slice[]{new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
}
| public void testGetSlice() {
final AbstractDataset d = Random.randn(new int[] {1, 2, 3, 4});
LazyDataset ld = new LazyDataset("", AbstractDataset.INT, new int[] {1, 2, 3, 4}, new ILazyLoader() {
@Override
public boolean isFileReadable() {
return true;
}
@Override
public AbstractDataset getDataset(IMonitor mon, int[] shape, int[] start, int[] stop, int[] step)
throws Exception {
return d.getSlice(mon, start, stop, step);
}
});
Slice[] slice;
slice = new Slice[]{null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", d, ld.getSlice());
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null));
Assert.assertEquals("Full slice", d, ld.getSlice((Slice) null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, null));
Assert.assertEquals("Full slice", d, ld.getSlice(null, null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], null, new int[] {1, 1, 1, 1}));
Assert.assertEquals("Full slice", d, ld.getSlice(new int[4], new int[] { 1, 2, 3, 4 }, new int[] { 1, 1, 1, 1 }));
Assert.assertEquals("Part slice", d.getSlice(slice), ld.getSlice(slice));
AbstractDataset nd;
ld.setShape(1, 1, 1, 2, 3, 4);
nd = d.getView();
nd.setShape(1, 1, 1, 2, 3, 4);
slice = new Slice[]{null, null, null, new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
ld.setShape(2, 3, 4);
nd = d.getView();
nd.setShape(2, 3, 4);
slice = new Slice[]{new Slice(1), null, new Slice(1, 3)};
Assert.assertEquals("Full slice", nd, ld.getSlice());
Assert.assertEquals("Part slice", nd.getSlice(slice), ld.getSlice(slice));
}
|
diff --git a/src/net/ooici/eoi/datasetagent/impl/UsgsAgent.java b/src/net/ooici/eoi/datasetagent/impl/UsgsAgent.java
index ab5e4fa..b3e7aeb 100644
--- a/src/net/ooici/eoi/datasetagent/impl/UsgsAgent.java
+++ b/src/net/ooici/eoi/datasetagent/impl/UsgsAgent.java
@@ -1,1670 +1,1670 @@
/*
* File Name: UsgsAgent.java
* Created on: Dec 20, 2010
*/
package net.ooici.eoi.datasetagent.impl;
import ion.core.IonException;
import ion.core.utils.GPBWrapper;
import ion.core.utils.IonUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.ooici.eoi.datasetagent.obs.IObservationGroup;
import net.ooici.eoi.datasetagent.obs.IObservationGroup.DataType;
import net.ooici.eoi.datasetagent.obs.ObservationGroupImpl;
import net.ooici.eoi.netcdf.VariableParams;
import net.ooici.eoi.netcdf.VariableParams.StandardVariable;
import net.ooici.eoi.datasetagent.AbstractAsciiAgent;
import net.ooici.eoi.datasetagent.AgentFactory;
import net.ooici.eoi.datasetagent.AgentUtils;
import net.ooici.eoi.netcdf.NcDumpParse;
import net.ooici.services.dm.IngestionService.DataAcquisitionCompleteMessage.StatusCode;
import net.ooici.services.sa.DataSource.EoiDataContextMessage;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import ucar.nc2.dataset.NetcdfDataset;
/**
* The UsgsAgent class is designed to fulfill updates for datasets which originate from USGS services. Ensure the update context (
* {@link EoiDataContextMessage}) to be passed to {@link #doUpdate(EoiDataContextMessage, HashMap)} has been constructed for USGS agents by
* checking the result of {@link EoiDataContextMessage#getSourceType()}
*
* @author cmueller
* @author tlarocque
* @version 1.0
* @see {@link EoiDataContextMessage#getSourceType()}
* @see {@link AgentFactory#getDatasetAgent(net.ooici.services.sa.DataSource.SourceType)}
*/
public class UsgsAgent extends AbstractAsciiAgent {
/**
* NOTE: this Object uses classes from org.jdom.* The JDOM library is included as a transitive dependency from
* ooi-netcdf-full-4.2.4.jar. Should the JDOM jar be included explicitly??
*
* TODO: check that each element selected by the xpath queries defined below are required per the WaterML1.1 spec. When these elements
* are selected via xpath NULLs are not checked. If an element is not required, missing values will cause NPE
*/
/** Static Fields */
static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UsgsAgent.class);
private static final SimpleDateFormat valueSdf;
private static final SimpleDateFormat inSdf;
private static int currentGroupId = -1;
private static final String USR_HOME = System.getProperty("user.home");
/** Maths */
public static final double CONVERT_FT_TO_M = 0.3048;
public static final double CONVERT_FT3_TO_M3 = Math.pow(CONVERT_FT_TO_M, 3);
private boolean isDailyValue = false;
private WSType wsType = WSType.IV;
private String data_url;
/** Static Initializer */
static {
valueSdf = new SimpleDateFormat("yyyy-MM-dd'T'HHmmss.sssZ");
valueSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
inSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
inSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
}
enum WSType {
IV,
DV,
IDV
}
/** Used to convert qualifier code to a byte storage value */
enum Qualifier {
PROVISIONAL("P", (byte) 1), APPROVED("A", (byte) 2);
static final byte DEFAULT_VALUE = 0;
final String code;
final byte byteValue;
Qualifier(String code, byte byteValue) {
this.code = code;
this.byteValue = byteValue;
}
public static byte getByteValue(String code) {
byte result = DEFAULT_VALUE;
for (Qualifier value : Qualifier.values()) {
if (value.code.equals(code)) {
result = value.byteValue;
break;
}
}
return result;
}
}
/**
* Constructs a URL from the given data <code>context</code> by appending necessary USGS-specific query string parameters to the base URL
* returned by <code>context.getBaseUrl()</code>. This URL may subsequently be passed through {@link #acquireData(String)} to procure
* updated data according to the <code>context</code> given here. Requests may be built differently depending on which USGS service
* <code>context.getBaseUrl()</code> specifies. Valid services include the WaterService webservice and the DailyValues service.
*
* @param context
* the current or required state of a USGS dataset providing context for building data requests to fulfill dataset updates
* @return A dataset update request URL built from the given <code>context</code> against a USGS service.
*/
@Override
public String buildRequest() {
log.debug("");
log.info("Building Request for context [" + context.toString() + "...]");
String result = "";
String baseurl = context.getBaseUrl();
if (baseurl.endsWith("nwis/iv?")) {
result = buildWaterServicesIVRequest();
} else if (baseurl.endsWith("nwis/dv?")) {
result = buildWaterServicesDVRequest();
wsType = WSType.DV;
} else if (baseurl.endsWith("NWISQuery/GetDV1?")) {
result = buildInterimWaterServicesDVRequest();
wsType = WSType.IDV;
}
// <editor-fold defaultstate="collapsed" desc="OLD - COMMENTED">
// String baseUrl = context.getBaseUrl();
// String sTimeString = context.getStartTime();
// String eTimeString = context.getEndTime();
// String properties[] = context.getPropertyList().toArray(new String[0]);
// String siteCodes[] = context.getStationIdList().toArray(new String[0]);
/** TODO: null-check here */
/** Configure the date-time parameter */
// Date sTime = null;
// Date eTime = null;
// DateFormat usgsUrlSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
// if (isDailyQuery) {
// usgsUrlSdf = new SimpleDateFormat("yyyy-MM-dd");
// }
// usgsUrlSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// try {
// sTime = AgentUtils.ISO8601_DATE_FORMAT.parse(sTimeString);
// sTimeString = usgsUrlSdf.format(sTime);
// } catch (ParseException e) {
// log.error("Error parsing start time - the start time will not be specified", e);
// sTimeString = null;
//// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.START_TIME + "Unparsable value = " + sTimeString, e);
// }
//
// if (sTimeString == null) {
// sTimeString =
// }
//
// try {
// eTime = AgentUtils.ISO8601_DATE_FORMAT.parse(eTimeString);
// eTimeString = usgsUrlSdf.format(eTime);
// } catch (ParseException e) {
// eTimeString = null;
// log.error("Error parsing end time - the end time will not be specified", e);
//// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.END_TIME + "Unparsable value = " + eTimeString, e);
// }
//
//
// if (isDailyQuery) {
// // http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?SiteNum=01463500&ParameterCode=00060&StatisticCode=00003&StartDate=2003-01-01
// // http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?SiteNum=01463500&ParameterCode=00060&StatisticCode=00003&StartDate=2003-01-01&EndDate=2011-03-15
// result.append(baseUrl);
// result.append("SiteNum=").append(siteCodes[0]);
// result.append("&ParameterCode=").append(properties[0]);
// result.append("&StatisticCode=00003");//Mean only for now
// if (sTimeString != null && !sTimeString.isEmpty()) {
// result.append("&StartDate=").append(sTimeString);
// }
// if (eTimeString != null && !eTimeString.isEmpty()) {
// result.append("&EndDate=").append(eTimeString);
// }
// } else {
// /** Build the propertiesString*/
// StringBuilder propertiesString = new StringBuilder();
// for (String property : properties) {
// if (null != property) {
// propertiesString.append(property.trim()).append(",");
// }
// }
// if (propertiesString.length() > 0) {
// propertiesString.deleteCharAt(propertiesString.length() - 1);
// }
//
// /** Build the list of sites (siteCSV)*/
// StringBuilder siteCSV = new StringBuilder();
// for (String siteCode : siteCodes) {
// if (null != siteCode) {
// siteCSV.append(siteCode.trim()).append(",");
// }
// }
// if (siteCSV.length() > 0) {
// siteCSV.deleteCharAt(siteCSV.length() - 1);
// }
//
// /** Build the query URL */
// result.append(baseUrl);
// result.append("&sites=").append(siteCSV);
// result.append("¶meterCd=").append(propertiesString);
// if (sTimeString != null && !sTimeString.isEmpty()) {
// result.append("&startDT=").append(sTimeString);
// }
// if (eTimeString != null && !eTimeString.isEmpty()) {
// result.append("&endDT=").append(eTimeString);
// }
// }
// </editor-fold>
data_url = result.toString();
log.debug("... built request: [" + data_url + "]");
return data_url;
}
private String buildWaterServicesIVRequest() {
StringBuilder result = new StringBuilder();
String baseUrl = context.getBaseUrl();
// String sTimeString = context.getStartTime();
// String eTimeString = context.getEndTime();
String properties[] = context.getPropertyList().toArray(new String[0]);
String siteCodes[] = context.getStationIdList().toArray(new String[0]);
/** TODO: null-check here */
/** Configure the date-time parameter */
Date sTime = null;
Date eTime = null;
if (context.hasStartDatetimeMillis()) {
sTime = new Date(context.getStartDatetimeMillis());
}
if (context.hasEndDatetimeMillis()) {
eTime = new Date(context.getEndDatetimeMillis());
}
// try {
// sTime = AgentUtils.ISO8601_DATE_FORMAT.parse(sTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.START_TIME + "Unparsable value = " + sTimeString, e);
// }
// try {
// eTime = AgentUtils.ISO8601_DATE_FORMAT.parse(eTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.END_TIME + "Unparsable value = " + eTimeString, e);
// }
DateFormat usgsUrlSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
usgsUrlSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String sTimeString = usgsUrlSdf.format(sTime);
String eTimeString = usgsUrlSdf.format(eTime);
/** Build the propertiesString*/
StringBuilder propertiesString = new StringBuilder();
for (String property : properties) {
if (null != property) {
propertiesString.append(property.trim()).append(",");
}
}
if (propertiesString.length() > 0) {
propertiesString.setLength(propertiesString.length() - 1);
}
/** Build the list of sites (siteCSV)*/
StringBuilder siteCSV = new StringBuilder();
for (String siteCode : siteCodes) {
if (null != siteCode) {
siteCSV.append(siteCode.trim()).append(",");
}
}
if (siteCSV.length() > 0) {
siteCSV.setLength(siteCSV.length() - 1);
}
/** Build the query URL */
result.append(baseUrl).append("&format=waterml,1.1");
result.append("&sites=").append(siteCSV);
result.append("¶meterCd=").append(propertiesString);
result.append("&startDT=").append(sTimeString);
result.append("&endDT=").append(eTimeString);
return result.toString();
}
private String buildInterimWaterServicesDVRequest() {
StringBuilder result = new StringBuilder();
String baseUrl = context.getBaseUrl();
// String sTimeString = context.getStartTime();
// String eTimeString = context.getEndTime();
String properties[] = context.getPropertyList().toArray(new String[0]);
String siteCodes[] = context.getStationIdList().toArray(new String[0]);
/** TODO: null-check here */
/** Configure the date-time parameter */
Date sTime = null;
Date eTime = null;
if (context.hasStartDatetimeMillis()) {
sTime = new Date(context.getStartDatetimeMillis());
}
// try {
// sTime = AgentUtils.ISO8601_DATE_FORMAT.parse(sTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.START_TIME + "Unparsable value = " + sTimeString, e);
// }
if (context.hasEndDatetimeMillis()) {
eTime = new Date(context.getEndDatetimeMillis());
}
// try {
// eTime = AgentUtils.ISO8601_DATE_FORMAT.parse(eTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.END_TIME + "Unparsable value = " + eTimeString, e);
// }
DateFormat usgsUrlSdf = new SimpleDateFormat("yyyy-MM-dd");
usgsUrlSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String sTimeString = usgsUrlSdf.format(sTime);
String eTimeString = usgsUrlSdf.format(eTime);
//TODO: If eTimeString is empty/null, set to "now"
/** Build the query URL */
result.append(baseUrl);
result.append("SiteNum=").append(siteCodes[0]);
result.append("&ParameterCode=").append(properties[0]);
result.append("&StatisticCode=00003");//Mean only for now
if (sTimeString != null && !sTimeString.isEmpty()) {
result.append("&StartDate=").append(sTimeString);
}
if (eTimeString != null && !eTimeString.isEmpty()) {
result.append("&EndDate=").append(eTimeString);
}
return result.toString();
}
private String buildWaterServicesDVRequest() {
StringBuilder result = new StringBuilder();
String baseUrl = context.getBaseUrl();
// String sTimeString = context.getStartTime();
// String eTimeString = context.getEndTime();
String properties[] = context.getPropertyList().toArray(new String[0]);
String siteCodes[] = context.getStationIdList().toArray(new String[0]);
/** TODO: null-check here */
/** Configure the date-time parameter */
Date sTime = null;
Date eTime = null;
if (context.hasStartDatetimeMillis()) {
sTime = new Date(context.getStartDatetimeMillis());
}
if (context.hasEndDatetimeMillis()) {
eTime = new Date(context.getEndDatetimeMillis());
}
// try {
// sTime = AgentUtils.ISO8601_DATE_FORMAT.parse(sTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.START_TIME + "Unparsable value = " + sTimeString, e);
// }
// try {
// eTime = AgentUtils.ISO8601_DATE_FORMAT.parse(eTimeString);
// } catch (ParseException e) {
// throw new IllegalArgumentException("Could not convert DATE string for context key " + DataSourceRequestKeys.END_TIME + "Unparsable value = " + eTimeString, e);
// }
DateFormat usgsUrlSdf = new SimpleDateFormat("yyyy-MM-dd");
usgsUrlSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String sTimeString = usgsUrlSdf.format(sTime);
String eTimeString = usgsUrlSdf.format(eTime);
/** Build the propertiesString*/
StringBuilder propertiesString = new StringBuilder();
for (String property : properties) {
if (null != property) {
propertiesString.append(property.trim()).append(",");
}
}
if (propertiesString.length() > 0) {
propertiesString.setLength(propertiesString.length() - 1);
}
/** Build the list of sites (siteCSV)*/
StringBuilder siteCSV = new StringBuilder();
for (String siteCode : siteCodes) {
if (null != siteCode) {
siteCSV.append(siteCode.trim()).append(",");
}
}
if (siteCSV.length() > 0) {
siteCSV.setLength(siteCSV.length() - 1);
}
/** Build the query URL */
result.append(baseUrl).append("&format=waterml,1.1");
result.append("&sites=").append(siteCSV);
result.append("¶meterCd=").append(propertiesString);
result.append("&statCd=00003");
result.append("&startDT=").append(sTimeString);
result.append("&endDT=").append(eTimeString);
return result.toString();
}
/**
* Parses the given <code>asciiData</code> for any signs of error
*
* @param asciiData
* <code>String</code> data as retrieved from {@link #acquireData(String)}
*
* @throws AsciiValidationException
* When the given <code>asciiData</code> is invalid or cannot be validated
*/
@Override
protected void validateData(String asciiData) {
super.validateData(asciiData);
StringReader sr = new StringReader(asciiData);
BufferedReader br = new BufferedReader(sr);
String firstLine = null;
try {
firstLine = br.readLine();
} catch (IOException e) {
throw new AsciiValidationException("Could not read the ascii input data during validation.", e);
}
/* Check the response for errors by looking for the word "Error"
* ...sometimes the response will be an error even though the
* connection's resonse code returns "200 OK" */
if (null != firstLine && firstLine.matches("Error [0-9][0-9][0-9] \\- .*")) {
int errStart = firstLine.indexOf("Error ");
int msgStart = firstLine.indexOf(" - ");
String respCode = firstLine.substring(errStart + 6, errStart + 9);
String respMsg = firstLine.substring(msgStart + 3);
throw new AsciiValidationException(new StringBuilder("Received HTTP Error ").append(respCode).append(" with response message: \"").append(respMsg).append("\"").toString());
}
}
/**
* Parses the given USGS <code>String</code> data (XML) as a list of <code>IObservationGroup</code> objects
*
* @param asciiData
* XML (<code>String</code>) data passed to this method from {@link #acquireData(String)}
*
* @return a list of <code>IObservationGroup</code> objects representing the observations parsed from the given <code>asciiData</code>
*/
@Override
protected List<IObservationGroup> parseObs(String asciiData) {
log.debug("");
log.info("Parsing observations from data [" + asciiData.substring(0, Math.min(asciiData.length(), 40)) + "...]");
List<IObservationGroup> obsList = new ArrayList<IObservationGroup>();
StringReader srdr = new StringReader(asciiData);
try {
switch (wsType) {
case IV:
obsList.add(wsIV_parseObservations(srdr));
break;
case DV:
obsList.add(wsDV_parseObservations(srdr));
break;
case IDV:
obsList.add(wsIDV_parseObservations(srdr));
break;
}
} finally {
if (srdr != null) {
srdr.close();
}
}
return obsList;
}
/**
* Parses the String data from the given reader into a list of observation groups.<br />
* <br />
* <b>Note:</b><br />
* The given reader is guaranteed to return from this method in a <i>closed</i> state.
*
* @param rdr
* a <code>Reader</code> object linked to a stream of USGS ascii data from the Waterservices Service
* @return a List of IObservationGroup objects if observations are parsed, otherwise this list will be empty
*/
public IObservationGroup wsIV_parseObservations(Reader rdr) {
/* TODO: Fix exception handling in this method, it is too generic; try/catch blocks should be as confined as possible */
/** XPATH queries */
final String XPATH_ELEMENT_TIME_SERIES = ".//ns1:timeSeries";
final String XPATH_ELEMENT_SITE_CODE = "./ns1:sourceInfo/ns1:siteCode";
final String XPATH_ATTRIBUTE_AGENCY_CODE = "./ns1:sourceInfo/ns1:siteCode/@agencyCode";
final String XPATH_ELEMENT_LATITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:latitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_LONGITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:longitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_VALUE = "./ns1:values/ns1:value";
final String XPATH_ELEMENT_VARIABLE_CODE = "./ns1:variable/ns1:variableCode";
final String XPATH_ELEMENT_VARIABLE_NAME = "./ns1:variable/ns1:variableName";
final String XPATH_ELEMENT_VARIABLE_NaN_VALUE = "./ns1:variable/ns1:noDataValue";
final String XPATH_ATTRIBUTE_QUALIFIERS = "./@qualifiers";
final String XPATH_ATTRIBUTE_DATETIME = "./@dateTime";
IObservationGroup obs = null;
SAXBuilder builder = new SAXBuilder();
Document doc = null;
String datetime = "[no date information]"; /* datetime defined here (outside try) for error reporting */
try {
doc = builder.build(rdr);
/** Grab Global Attributes (to be copied into each observation group */
Namespace ns1 = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.1/");
// Namespace ns2 = Namespace.getNamespace("ns2", "http://waterservices.usgs.gov/WaterML-1.1.xsd");
// Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema");
Element root = doc.getRootElement();
Element queryInfo = root.getChild("queryInfo", ns1);
Map<String, String> globalAttributes = new HashMap<String, String>();
/* Extract the Global Attributes */
/* title */
String queryUrl = xpathSafeSelectValue(queryInfo, ".//ns2:queryURL", null);
// globalAttributes.put("title", "USGS rivers data timeseries. Requested from \"" + queryUrl + "\"");
String siteName = xpathSafeSelectValue(root, "//ns1:sourceInfo/ns1:siteName", null);
String locationParam = xpathSafeSelectValue(root, "//ns1:queryInfo/ns1:criteria/ns1:locationParam", null);
locationParam = locationParam.substring(locationParam.indexOf(":") + 1, locationParam.indexOf("]"));
String variableName = xpathSafeSelectValue(root, "//ns1:variable/ns1:variableName", null);
int cut = variableName.indexOf(",");
if (cut >= 1) {
variableName = variableName.substring(0, cut);
}
String title = siteName + " (" + locationParam + ") - Instantaneous Value";// + variableName;
title = title.replace(",", "").replace(".", "");
globalAttributes.put("title", title);
globalAttributes.put("institution", "USGS NWIS");
/* history */
globalAttributes.put("history", "Converted from WaterML1.1 to OOI CDM by " + UsgsAgent.class.getName());
/* references */
globalAttributes.put("references", "http://waterservices.usgs.gov/rest/WOF-IV-Service.html");
/* source */
globalAttributes.put("source", "Instantaneous Values Webservice (http://waterservices.usgs.gov/mwis/iv?)");
/* conventions - from schema */
// globalAttributes.put("Conventions", "CF-1.5");
/* Data URL */
/* CAN'T have this because it changes every update and we don't have a way of merging attributes across multiple updates */
// globalAttributes.put("data_url", data_url);
/** Get a list of provided time series */
List<?> timeseriesList = XPath.selectNodes(doc, XPATH_ELEMENT_TIME_SERIES);
/** Build an observation group for each unique sitecode */
Object nextTimeseries = null;
Iterator<?> iterTimeseries = timeseriesList.iterator();
boolean hasWaterSurface;
while (iterTimeseries.hasNext()) {
hasWaterSurface = false;
/* Grab the next element */
nextTimeseries = iterTimeseries.next();
if (null == nextTimeseries) {
continue;
}
/** Grab data for the current site */
String stnId = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_SITE_CODE)).getTextTrim();
String latitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LATITUDE)).getTextTrim();
String longitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LONGITUDE)).getTextTrim();
String noDataString = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_NaN_VALUE)).getTextTrim();
float lat = Float.parseFloat(latitude);
float lon = Float.parseFloat(longitude);
// float noDataValue = Float.parseFloat(noDataString);
/* Check to see if the observation group already exists */
if (obs == null) {
/* Create a new observation group if one does not currently exist */
obs = new ObservationGroupImpl(getNextGroupId(), stnId, lat, lon);
}
/** Grab variable data */
String variableCode = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_CODE)).getTextTrim();
// String variableUnits = getUnitsForVariableCode(variableCode);
// String variableName = getStdNameForVariableCode(variableCode);
/** Add each timeseries value (observation) to the observation group */
/* Get a list of each observation */
List<?> observationList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUE);
/* Add an observation for each "value" parsed */
Object next = null;
Iterator<?> iter = observationList.iterator();
while (iter.hasNext()) {
/* Grab the next element */
next = iter.next();
if (null == next) {
continue;
}
/* Grab observation data */
String qualifier = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_QUALIFIERS)).getValue();
datetime = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_DATETIME)).getValue();
String value = ((Element) next).getTextTrim();
datetime = datetime.replaceAll("\\:", "");
/* Convert observation data */
int time = 0;
float data = 0;
float dpth = 0;
VariableParams name = null;
time = (int) (valueSdf.parse(datetime).getTime() * 0.001);
// data = Float.parseFloat(value);
name = getDataNameForVariableCode(variableCode);
/* Check to see if this is the waterSurface var */
hasWaterSurface = (!hasWaterSurface) ? name == VariableParams.StandardVariable.RIVER_WATER_SURFACE_HEIGHT.getVariableParams() : hasWaterSurface;
/* DON'T EVER CONVERT - Only convert data if we are dealing with Steamflow */
// if (name == VariableParams.RIVER_STREAMFLOW) {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value) * CONVERT_FT3_TO_M3); /* convert from (f3 s-1) --> (m3 s-1) */
// } else {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
// }
data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
dpth = 0;
/* Add the observation data */
obs.addObservation(time, dpth, data, new VariableParams(name, DataType.FLOAT));
/* Add the data observation qualifier */
byte qualifier_value = Qualifier.getByteValue(qualifier.toString());
obs.addObservation(time, dpth, qualifier_value, new VariableParams(StandardVariable.USGS_QC_FLAG, DataType.BYTE));
}
/* If the group has waterSurface, add a the datum variable */
if (hasWaterSurface) {
obs.addScalarVariable(new VariableParams(VariableParams.StandardVariable.RIVER_WATER_SURFACE_REF_DATUM_ALTITUDE, DataType.FLOAT), 0f);
}
}
obs.addAttributes(globalAttributes);
} catch (JDOMException ex) {
log.error("Error while parsing xml from the given reader", ex);
} catch (IOException ex) {
log.error("General IO exception. Please see stack-trace", ex);
} catch (ParseException ex) {
log.error("Could not parse date information from XML result for: " + datetime, ex);
}
return obs;
}
/**
* Parses the String data from the given reader into a list of observation groups.<br />
* <br />
* <b>Note:</b><br />
* The given reader is guaranteed to return from this method in a <i>closed</i> state.
*
* @param rdr
* a <code>Reader</code> object linked to a stream of USGS ascii data from the Daily Values Service
* @return a List of IObservationGroup objects if observations are parsed, otherwise this list will be empty
*/
public IObservationGroup wsIDV_parseObservations(Reader rdr) {
/* TODO: Fix exception handling in this method, it is too generic; try/catch blocks should be as confined as possible */
/** XPATH queries */
final String XPATH_ELEMENT_TIME_SERIES = ".//ns1:timeSeries";
final String XPATH_ELEMENT_SITE_CODE = "./ns1:sourceInfo/ns1:siteCode";
final String XPATH_ATTRIBUTE_AGENCY_CODE = "./ns1:sourceInfo/ns1:siteCode/@agencyCode";
final String XPATH_ELEMENT_LATITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:latitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_LONGITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:longitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_VALUE = "./ns1:values/ns1:value";
final String XPATH_ELEMENT_VARIABLE_CODE = "./ns1:variable/ns1:variableCode";
final String XPATH_ELEMENT_VARIABLE_NAME = "./ns1:variable/ns1:variableName";
final String XPATH_ELEMENT_VARIABLE_NaN_VALUE = "./ns1:variable/ns1:NoDataValue";
final String XPATH_ATTRIBUTE_QUALIFIERS = "./@qualifiers";
final String XPATH_ATTRIBUTE_DATETIME = "./@dateTime";
IObservationGroup obs = null;
SAXBuilder builder = new SAXBuilder();
Document doc = null;
String datetime = "[no date information]"; /* datetime defined here (outside try) for error reporting */
try {
doc = builder.build(rdr);
/** Grab Global Attributes (to be copied into each observation group */
Namespace ns = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.0/");
// Namespace ns1 = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.1/");
// Namespace ns2 = Namespace.getNamespace("ns2", "http://waterservices.usgs.gov/WaterML-1.1.xsd");
// Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema");
Element root = doc.getRootElement();
root.setNamespace(ns);
// Element queryInfo = root.getChild("queryInfo", ns);
Map<String, String> globalAttributes = new HashMap<String, String>();
/* Extract the Global Attributes */
/* title */
// String queryUrl = xpathSafeSelectValue(queryInfo, ".//ns2:queryURL", null);
String siteName = xpathSafeSelectValue(root, "//ns1:sourceInfo/ns1:siteName", null);
String locationParam = xpathSafeSelectValue(root, "//ns1:queryInfo/ns1:criteria/ns1:locationParam", null);
locationParam = locationParam.substring(locationParam.indexOf(":") + 1, locationParam.indexOf("/"));
// String variableName = xpathSafeSelectValue(root, "//ns1:variable/ns1:variableName", null);
// String dataType = xpathSafeSelectValue(root, "//ns1:variable/ns1:dataType", null);
String title = siteName + " (" + locationParam + ") - Daily Values";// + dataType + " " + variableName;
title = title.replace(",", "").replace(".", "");
globalAttributes.put("title", title);
globalAttributes.put("institution", "USGS NWIS");
/* history */
globalAttributes.put("history", "Converted from WaterML1.0 to OOI CDM by " + UsgsAgent.class.getName());
/* references */
globalAttributes.put("references", "http://waterservices.usgs.gov/rest/USGS-DV-Service.html (interim)");
/* source */
globalAttributes.put("source", "Daily Values Webservice (http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?)");
/* conventions - from schema */
// globalAttributes.put("Conventions", "CF-1.5");
/* Data URL */
/* CAN'T have this because it changes every update and we don't have a way of merging attributes across multiple updates */
// globalAttributes.put("data_url", data_url);
/** Get a list of provided time series */
List<?> timeseriesList = XPath.selectNodes(root, ".//ns1:timeSeries");
// List<?> timeseriesList = XPath.selectNodes(doc, XPATH_ELEMENT_TIME_SERIES);
// List<?> timeseriesList = XPath.selectNodes(doc, ".//timeSeries");
// List<?> timeseriesList = root.getChildren("timeSeries", ns);
// System.out.println("Total timeseries in doc: " + timeseriesList.size());
/** Build an observation group for each unique sitecode */
Object nextTimeseries = null;
Iterator<?> iterTimeseries = timeseriesList.iterator();
while (iterTimeseries.hasNext()) {
/* Grab the next element */
nextTimeseries = iterTimeseries.next();
if (null == nextTimeseries) {
continue;
}
/** Grab data for the current site */
String stnId = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_SITE_CODE)).getTextTrim();
String latitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LATITUDE)).getTextTrim();
String longitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LONGITUDE)).getTextTrim();
String noDataString = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_NaN_VALUE)).getTextTrim();
float lat = Float.parseFloat(latitude);
float lon = Float.parseFloat(longitude);
// float noDataValue = Float.parseFloat(noDataString);
/* Check to see if the observation group already exists */
if (obs == null) {
/* Create a new observation group if one does not currently exist */
obs = new ObservationGroupImpl(getNextGroupId(), stnId, lat, lon);
}
/** Grab variable data */
String variableCode = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_CODE)).getTextTrim();
// String variableUnits = getUnitsForVariableCode(variableCode);
// String variableName = getStdNameForVariableCode(variableCode);
/** Add each timeseries value (observation) to the observation group */
/* Get a list of each observation */
List<?> observationList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUE);
/* Add an observation for each "value" parsed */
Object next = null;
Iterator<?> iter = observationList.iterator();
while (iter.hasNext()) {
/* Grab the next element */
next = iter.next();
if (null == next) {
continue;
}
/* Grab observation data */
String qualifier = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_QUALIFIERS)).getValue();
datetime = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_DATETIME)).getValue();
String value = ((Element) next).getTextTrim();
datetime = datetime.replaceAll("\\:", "");
/* Convert observation data */
int time = 0;
float data = 0;
float dpth = 0;
VariableParams name = null;
final SimpleDateFormat dvInputSdf;
dvInputSdf = new SimpleDateFormat("yyyy-MM-dd'T'HHmmss");
dvInputSdf.setTimeZone(TimeZone.getTimeZone("UTC"));
time = (int) (dvInputSdf.parse(datetime).getTime() * 0.001);
// data = Float.parseFloat(value);
name = getDataNameForVariableCode(variableCode);
/* DON'T EVER CONVERT - Only convert data if we are dealing with Steamflow) */
// if (name == VariableParams.RIVER_STREAMFLOW) {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value) * CONVERT_FT3_TO_M3); /* convert from (f3 s-1) --> (m3 s-1) */
// } else {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
// }
data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
dpth = 0;
/* Add the observation data */
obs.addObservation(time, dpth, data, new VariableParams(name, DataType.FLOAT));
/* Add the data observation qualifier */
byte qualifier_value = Qualifier.getByteValue(qualifier.toString());
obs.addObservation(time, dpth, qualifier_value, new VariableParams(StandardVariable.USGS_QC_FLAG, DataType.BYTE));
}
// /** Grab attributes */
// Map<String, String> tsAttributes = new TreeMap<String, String>();
//
//
// /* Extract timeseries-specific attributes */
// String sitename = xpathSafeSelectValue(nextTimeseries, "//ns1:siteName", "[n/a]");
// String network = xpathSafeSelectValue(nextTimeseries, "//ns1:siteCode/@network", "[n/a]");
// String agency = xpathSafeSelectValue(nextTimeseries, "//ns1:siteCode/@agencyCode", "[n/a]");
// String sCode = xpathSafeSelectValue(nextTimeseries, "//ns1:siteCode", "[n/a]");
// tsAttributes.put("institution", new StringBuilder().append(sitename).append(" (network:").append(network).append("; agencyCode:").append(agency).append("; siteCode:").append(sCode).append(";)").toString());
//
// String method = xpathSafeSelectValue(nextTimeseries, ".//ns1:values//ns1:methodDescription", "[n/a]");
// tsAttributes.put("source", method);
//
//
//
// /** Add global and timeseries attributes */
// obs.addAttributes(tsAttributes);
}
obs.addAttributes(globalAttributes);
} catch (JDOMException ex) {
log.error("Error while parsing xml from the given reader", ex);
} catch (IOException ex) {
log.error("General IO exception. Please see stack-trace", ex);
} catch (ParseException ex) {
log.error("Could not parse date information from XML result for: " + datetime, ex);
}
return obs;
}
/**
* Parses the String data from the given reader into a list of observation groups.<br />
* <br />
* <b>Note:</b><br />
* The given reader is guaranteed to return from this method in a <i>closed</i> state.
*
* @param rdr
* a <code>Reader</code> object linked to a stream of USGS ascii data from the Waterservices Service
* @return a List of IObservationGroup objects if observations are parsed, otherwise this list will be empty
*/
public IObservationGroup wsDV_parseObservations(Reader rdr) {
/* TODO: Fix exception handling in this method, it is too generic; try/catch blocks should be as confined as possible */
/** XPATH queries */
final String XPATH_ELEMENT_TIME_SERIES = ".//ns1:timeSeries";
final String XPATH_ELEMENT_SITE_CODE = "./ns1:sourceInfo/ns1:siteCode";
final String XPATH_ATTRIBUTE_AGENCY_CODE = "./ns1:sourceInfo/ns1:siteCode/@agencyCode";
final String XPATH_ELEMENT_LATITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:latitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_LONGITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:longitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_VALUES = "./ns1:values";
final String XPATH_ELEMENT_VALUE = "./ns1:value";
final String XPATH_ELEMENT_VARIABLE_CODE = "./ns1:variable/ns1:variableCode";
final String XPATH_ELEMENT_VARIABLE_NAME = "./ns1:variable/ns1:variableName";
final String XPATH_ELEMENT_VARIABLE_NaN_VALUE = "./ns1:variable/ns1:noDataValue";
final String XPATH_ATTRIBUTE_QUALIFIERS = "./@qualifiers";
final String XPATH_ATTRIBUTE_DATETIME = "./@dateTime";
IObservationGroup obs = null;
SAXBuilder builder = new SAXBuilder();
Document doc = null;
String datetime = "[no date information]"; /* datetime defined here (outside try) for error reporting */
try {
doc = builder.build(rdr);
/** Grab Global Attributes (to be copied into each observation group */
Namespace ns1 = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.1/");
// Namespace ns2 = Namespace.getNamespace("ns2", "http://waterservices.usgs.gov/WaterML-1.1.xsd");
// Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema");
Element root = doc.getRootElement();
Element queryInfo = root.getChild("queryInfo", ns1);
Map<String, String> globalAttributes = new HashMap<String, String>();
/* Extract the Global Attributes */
/* title */
String queryUrl = xpathSafeSelectValue(queryInfo, ".//ns2:queryURL", null);
// globalAttributes.put("title", "USGS rivers data timeseries. Requested from \"" + queryUrl + "\"");
String siteName = xpathSafeSelectValue(root, "//ns1:sourceInfo/ns1:siteName", null);
String locationParam = xpathSafeSelectValue(root, "//ns1:queryInfo/ns1:criteria/ns1:locationParam", null);
locationParam = locationParam.substring(locationParam.indexOf(":") + 1, locationParam.indexOf("]"));
String variableName = xpathSafeSelectValue(root, "//ns1:variable/ns1:variableName", null);
int cut = variableName.indexOf(",");
if (cut >= 1) {
variableName = variableName.substring(0, cut);
}
String title = siteName + " (" + locationParam + ") - Daily Value";// + variableName;
title = title.replace(",", "").replace(".", "");
globalAttributes.put("title", title);
globalAttributes.put("institution", "USGS NWIS");
/* history */
globalAttributes.put("history", "Converted from WaterML1.1 to OOI CDM by " + UsgsAgent.class.getName());
/* references */
globalAttributes.put("references", "http://waterservices.usgs.gov/rest/DV-Service.html");
/* source */
- globalAttributes.put("source", "Instantaneous Values Webservice (http://waterservices.usgs.gov/mwis/dv?)");
+ globalAttributes.put("source", "Daily Values Webservice (http://waterservices.usgs.gov/mwis/dv?)");
/* conventions - from schema */
// globalAttributes.put("Conventions", "CF-1.5");
/* Data URL */
/* CAN'T have this because it changes every update and we don't have a way of merging attributes across multiple updates */
// globalAttributes.put("data_url", data_url);
/** Get a list of provided time series */
List<?> timeseriesList = XPath.selectNodes(doc, XPATH_ELEMENT_TIME_SERIES);
/** Build an observation group for each unique sitecode */
Object nextTimeseries = null;
Iterator<?> iterTimeseries = timeseriesList.iterator();
boolean hasWaterSurface;
while (iterTimeseries.hasNext()) {
hasWaterSurface = false;
/* Grab the next element */
nextTimeseries = iterTimeseries.next();
if (null == nextTimeseries) {
continue;
}
/** Grab data for the current site */
String stnId = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_SITE_CODE)).getTextTrim();
String latitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LATITUDE)).getTextTrim();
String longitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LONGITUDE)).getTextTrim();
String noDataString = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_NaN_VALUE)).getTextTrim();
float lat = Float.parseFloat(latitude);
float lon = Float.parseFloat(longitude);
// float noDataValue = Float.parseFloat(noDataString);
/* Check to see if the observation group already exists */
if (obs == null) {
/* Create a new observation group if one does not currently exist */
obs = new ObservationGroupImpl(getNextGroupId(), stnId, lat, lon);
}
/** Grab variable data */
String variableCode = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_CODE)).getTextTrim();
// String variableUnits = getUnitsForVariableCode(variableCode);
// String variableName = getStdNameForVariableCode(variableCode);
VariableParams name = getDataNameForVariableCode(variableCode);
/* Check to see if this is the waterSurface var */
hasWaterSurface = (!hasWaterSurface) ? name == VariableParams.StandardVariable.RIVER_WATER_SURFACE_HEIGHT.getVariableParams() : hasWaterSurface;
/* May be multiple sets of values for a "variable" (i.e. middle, bottom, surface) */
List<?> valuesList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUES);
Iterator<?> valuesIter = valuesList.iterator();
Object valuesSet = null;
Pattern pattern = Pattern.compile("\\((.*)\\)");
Matcher match = null;
while (valuesIter.hasNext()) {
String varNameSuffix = "";
String longNameSuffix = "";
valuesSet = valuesIter.next();
if (valuesSet == null) {
continue;
}
Object method = XPath.selectSingleNode(valuesSet, "./ns1:method/ns1:methodDescription");
if (method != null) {
String methString = ((Element) method).getTextTrim();
if (methString != null & !methString.isEmpty()) {
longNameSuffix = methString;
match = pattern.matcher(methString);
if(match.find()) {
varNameSuffix = match.group(1);
} else {
varNameSuffix = methString;
}
varNameSuffix = varNameSuffix.toLowerCase().replace(" ", "_");
// varNameSuffix = methString.substring(methString.indexOf("(") + 1, methString.indexOf(")"));
}
}
// }
/** Add each timeseries value (observation) to the observation group */
/* Get a list of each observation */
// List<?> observationList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUE);
List<?> observationList = XPath.selectNodes(valuesSet, XPATH_ELEMENT_VALUE);
/* Add an observation for each "value" parsed */
Object next = null;
Iterator<?> iter = observationList.iterator();
while (iter.hasNext()) {
/* Grab the next element */
next = iter.next();
if (null == next) {
continue;
}
/* Grab observation data */
String qualifier = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_QUALIFIERS)).getValue();
datetime = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_DATETIME)).getValue();
String value = ((Element) next).getTextTrim();
// datetime = datetime.replaceAll("\\:", "").concat("Z");
/* Convert observation data */
int time = 0;
float data = 0;
float dpth = 0;
time = (int) (inSdf.parse(datetime).getTime() * 0.001);
// data = Float.parseFloat(value);
/* DON'T EVER CONVERT - Only convert data if we are dealing with Steamflow */
// if (name == VariableParams.RIVER_STREAMFLOW) {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value) * CONVERT_FT3_TO_M3); /* convert from (f3 s-1) --> (m3 s-1) */
// } else {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
// }
data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
dpth = 0;
/* Add the observation data */
// obs.addObservation(time, dpth, data, new VariableParams(name, DataType.FLOAT));
String vName = (!varNameSuffix.isEmpty()) ? name.getShortName().concat("_").concat(varNameSuffix) : name.getShortName();
String lName = (!longNameSuffix.isEmpty()) ? name.getDescription().concat(" ").concat(longNameSuffix) : name.getDescription();
obs.addObservation(time, dpth, data, new VariableParams(name.getStandardName(), vName, lName, name.getUnits(), DataType.FLOAT));
/* Add the data observation qualifier */
byte qualifier_value = Qualifier.getByteValue(qualifier.toString());
obs.addObservation(time, dpth, qualifier_value, new VariableParams(StandardVariable.USGS_QC_FLAG, DataType.BYTE));
}
}
/* If the group has waterSurface, add a the datum variable */
if (hasWaterSurface) {
obs.addScalarVariable(new VariableParams(VariableParams.StandardVariable.RIVER_WATER_SURFACE_REF_DATUM_ALTITUDE, DataType.FLOAT), 0f);
}
}
obs.addAttributes(globalAttributes);
} catch (JDOMException ex) {
log.error("Error while parsing xml from the given reader", ex);
} catch (IOException ex) {
log.error("General IO exception. Please see stack-trace", ex);
} catch (ParseException ex) {
log.error("Could not parse date information from XML result for: " + datetime, ex);
}
return obs;
}
private static String xpathSafeSelectValue(Object context, String path, String defaultValue, Namespace... namespaces) {
Object result = null;
try {
XPath xp = XPath.newInstance(path);
if (null != namespaces) {
for (Namespace namespace : namespaces) {
xp.addNamespace(namespace);
}
}
result = xp.selectSingleNode(context);
} catch (JDOMException ex) {
log.debug("Could not select node via XPath query: \"" + path + "\"", ex);
}
return xpathNodeValue(result, defaultValue);
}
/**
* <b>Note:</b><br />
* This method does not support all types of returns from XPath.selectSingleNode().
* It will currently support:<br />
* org.jdom.Attribute<br />
* org.jdom.Element<br />
* @param node
* @param defaultValue
* @return
*/
private static String xpathNodeValue(Object node, String defaultValue) {
/* Overwrite defaultValue if value can be retrieved from node */
if (node instanceof org.jdom.Attribute) {
defaultValue = ((org.jdom.Attribute) node).getValue();
} else if (node instanceof org.jdom.Element) {
defaultValue = ((org.jdom.Element) node).getText();
}
return defaultValue;
}
protected static int getCurrentGroupId() {
return currentGroupId;
}
protected static int getNextGroupId() {
return ++currentGroupId;
}
protected static VariableParams getDataNameForVariableCode(String variableCode) {
VariableParams result = null;
if ("00010".equals(variableCode)) {
result = VariableParams.StandardVariable.WATER_TEMPERATURE.getVariableParams();
} else if ("00060".equals(variableCode)) {
result = VariableParams.StandardVariable.RIVER_STREAMFLOW.getVariableParams();
} else if ("00065".equals(variableCode)) {
result = VariableParams.StandardVariable.RIVER_WATER_SURFACE_HEIGHT.getVariableParams();
} else if ("00045".equals(variableCode)) {
result = VariableParams.StandardVariable.RIVER_PRECIPITATION.getVariableParams();
} else if ("00095".equals(variableCode)) {
result = VariableParams.StandardVariable.USGS_SEA_WATER_CONDUCTIVITY.getVariableParams();
} else {
throw new IllegalArgumentException("Given variable code is not known: " + variableCode);
}
return result;
}
/**
* Converts the given list of <code>IObservationGroup</code>s to a {@link NetcdfDataset}, breaks that dataset into manageable sections
* and sends those data "chunks" to the ingestion service.
*
* @param obsList
* a group of observations as a list of <code>IObservationGroup</code> objects
*
* @return TODO:
*
* @see #obs2Ncds(IObservationGroup...)
* @see #sendNetcdfDataset(NetcdfDataset, String)
* @see #sendNetcdfDataset(NetcdfDataset, String, boolean)
*/
@Override
public String[] processDataset(IObservationGroup... obsList) {
List<String> ret = new ArrayList<String>();
NetcdfDataset ncds = null;
try {
ncds = obs2Ncds(obsList);
if (ncds != null) {
/* Send the dataset via the send dataset method of AbstractDatasetAgent */
ret.add(this.sendNetcdfDataset(ncds, "ingest"));
} else {
/* Send the an error via the send dataset method of AbstractDatasetAgent */
String err = "Abort from this update:: The returned NetcdfDataset is null";
this.sendDataErrorMsg(StatusCode.AGENT_ERROR, err);
ret.add(err);
}
} catch (IonException ex) {
ret.add(AgentUtils.getStackTraceString(ex));
}
return ret.toArray(new String[0]);
}
/*****************************************************************************************************************/
/* Testing */
/*****************************************************************************************************************/
public static void main(String[] args) throws IOException {
try {
ion.core.IonBootstrap.bootstrap();
} catch (Exception ex) {
log.error("Error bootstrapping", ex);
}
boolean dailyValues = false;
boolean makeRutgersSamples = false;
boolean makeUHSamples = false;
boolean makeMetadataTable = false;
boolean manual = true;
if (makeRutgersSamples) {
generateRutgersSamples(dailyValues);
}
if (makeUHSamples) {
generateUHSamples(dailyValues);
}
if (makeMetadataTable) {
generateRutgersMetadata(dailyValues);
}
if (manual) {
net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
cBldr.setIsInitial(true);
cBldr.setBaseUrl("http://waterservices.usgs.gov/nwis/iv?");
int switcher = 4;
try {
switch (switcher) {
case 1://test temp
// cBldr.setStartTime("2011-2-20T00:00:00Z");
// cBldr.setEndTime("2011-4-19T00:00:00Z");
//test temp
// cBldr.setStartTime("2011-2-20T00:00:00Z");
// cBldr.setEndTime("2011-4-19T00:00:00Z");
cBldr.setStartDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-2-20T00:00:00Z").getTime());
cBldr.setEndDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-4-19T00:00:00Z").getTime());
cBldr.addProperty("00010");
// cBldr.addStationId("01463500");
cBldr.addStationId("01646500");
break;
case 2://test discharge
cBldr.setStartDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-2-20T00:00:00Z").getTime());
cBldr.setEndDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-4-19T00:00:00Z").getTime());
cBldr.addProperty("00060");
// cBldr.addStationId("01463500");
cBldr.addStationId("01646500");
break;
case 3://test temp & discharge
cBldr.setStartDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-2-10T00:00:00Z").getTime());
cBldr.setEndDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-2-11T00:00:00Z").getTime());
cBldr.addProperty("00010");
cBldr.addProperty("00060");
// cBldr.addStationId("01463500");
cBldr.addStationId("01646500");
break;
case 4:
// cBldr.setBaseUrl("http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?");
cBldr.setBaseUrl("http://waterservices.usgs.gov/nwis/dv?");
cBldr.setStartDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-01-01T00:00:00Z").getTime());
// cBldr.setStartTime("2011-02-01T00:00:00Z");
cBldr.setEndDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-08-07T00:00:00Z").getTime());
cBldr.addProperty("00010");
cBldr.addProperty("00060");
cBldr.addProperty("00065");//gauge height
cBldr.addProperty("00045");//precip
cBldr.addProperty("00095");//??
cBldr.addStationId("01463500");
// cBldr.addStationId("01646500");
break;
case 5://test all supported parameters
cBldr.setStartDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-05-12T00:00:00Z").getTime());
cBldr.setEndDatetimeMillis(AgentUtils.ISO8601_DATE_FORMAT.parse("2011-05-13T00:00:00Z").getTime());
cBldr.addProperty("00010");
cBldr.addProperty("00060");
cBldr.addProperty("00065");//gauge height
cBldr.addProperty("00045");//precip
cBldr.addProperty("00095");//??
// cBldr.addStationId("01491000");
cBldr.addStationId("212359157502601");
break;
}
} catch (ParseException ex) {
throw new IOException("Error parsing time strings", ex);
}
// cBldr.setStartTime("2011-01-29T00:00:00Z");
// cBldr.setEndTime("2011-01-31T00:00:00Z");
// cBldr.addProperty("00010");
// cBldr.addProperty("00060");
// cBldr.addAllStationId(java.util.Arrays.asList(new String[] {"01184000", "01327750", "01357500", "01389500", "01403060", "01463500", "01578310", "01646500", "01592500", "01668000", "01491000", "02035000", "02041650", "01673000", "01674500", "01362500", "01463500", "01646500" }));
net.ooici.core.container.Container.Structure struct = AgentUtils.getUpdateInitStructure(GPBWrapper.Factory(cBldr.build()));
// runAgent(struct, AgentRunType.TEST_WRITE_OOICDM);
runAgent(struct, AgentRunType.TEST_WRITE_NC);
}
}
private static void generateRutgersMetadata(boolean dailyValues) throws IOException {
/** For each of the "R1" netcdf datasets (either local or remote)
*
* 1. get the last timestep of the data
* 2. get the list of global-attributes
* 3. build a delimited string with the following structure:
* attribute_1, attribute_2, attribute_3, ..., attribute_n
* value_1, value_2, value_3, ..., value_n
*
*/
// String[] datasetList = new String[]{"http://nomads.ncep.noaa.gov:9090/dods/nam/nam20110303/nam1hr_00z",
// "http://thredds1.pfeg.noaa.gov/thredds/dodsC/satellite/GR/ssta/1day",
// "http://tashtego.marine.rutgers.edu:8080/thredds/dodsC/cool/avhrr/bigbight/2010"};
Map<String, Map<String, String>> datasets = new TreeMap<String, Map<String, String>>(); /* Maps dataset name to an attributes map */
List<String> metaLookup = new ArrayList<String>();
/* Front-load the metadata list with the OOI required metadata */
metaLookup.add("title");
metaLookup.add("institution");
metaLookup.add("source");
metaLookup.add("history");
metaLookup.add("references");
metaLookup.add("Conventions");
metaLookup.add("summary");
metaLookup.add("comment");
metaLookup.add("data_url");
metaLookup.add("ion_time_coverage_start");
metaLookup.add("ion_time_coverage_end");
metaLookup.add("ion_geospatial_lat_min");
metaLookup.add("ion_geospatial_lat_max");
metaLookup.add("ion_geospatial_lon_min");
metaLookup.add("ion_geospatial_lon_max");
metaLookup.add("ion_geospatial_vertical_min");
metaLookup.add("ion_geospatial_vertical_max");
metaLookup.add("ion_geospatial_vertical_positive");
/* For now, don't add anything - this process will help us figure out what needs to be added *//* Generates samples for near-realtime high-resolution data */
String baseURL = "http://waterservices.usgs.gov/nwis/iv?";
long sTime, eTime;
try {
sTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2011-03-01T00:00:00Z").getTime();
eTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2011-03-10T00:00:00Z").getTime();
/* Generates samples for "historical" low-resolution data */
baseURL = "http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?";
sTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2003-01-01T00:00:00Z").getTime();
eTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2011-03-17T00:00:00Z").getTime();
} catch (ParseException ex) {
throw new IOException("Error parsing time string(s)", ex);
}
String prefix = (baseURL.endsWith("NWISQuery/GetDV1?")) ? "USGS-DV " : "USGS-WS ";
String[] disIds = new String[]{"01184000", "01327750", "01357500", "01389500", "01403060", "01463500", "01578310", "01646500", "01592500", "01668000", "01491000", "02035000", "02041650", "01673000", "01674500"};
String[] disNames = new String[]{"Connecticut", "Hudson", "Mohawk", "Passaic", "Raritan", "Delaware", "Susquehanna", "Potomac", "Patuxent", "Rappahannock", "Choptank", "James", "Appomattox", "Pamunkey", "Mattaponi"};
String[] tempIds = new String[]{"01362500", "01463500", "01646500"};
String[] tempNames = new String[]{"Hudson", "Delware", "Potomac"};
String dsName;
String[] resp;
for (int i = 0; i < disIds.length; i++) {
dsName = prefix + disNames[i] + "[" + disIds[i] + "]";
try {
net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
cBldr.setBaseUrl(baseURL);
cBldr.setStartDatetimeMillis(sTime);
cBldr.setEndDatetimeMillis(eTime);
cBldr.addProperty("00060");
cBldr.addStationId(disIds[i]);
net.ooici.core.container.Container.Structure struct = AgentUtils.getUpdateInitStructure(GPBWrapper.Factory(cBldr.build()));
resp = runAgent(struct, AgentRunType.TEST_NO_WRITE);
} catch (Exception e) {
e.printStackTrace();
datasets.put(dsName + " (FAILED)", null);
continue;
}
Map<String, String> dsMeta = NcDumpParse.parseToMap(resp[0]);
datasets.put(dsName, dsMeta);
/* TODO: Eventually we can make this loop external and perform a sort beforehand.
* this sort would frontload attributes which are found more frequently
* across multiple datasets
*/
for (String key : dsMeta.keySet()) {
if (!metaLookup.contains(key)) {
metaLookup.add(key);
}
}
}
for (int i = 0; i < tempIds.length; i++) {
dsName = prefix + disNames[i] + "[" + disIds[i] + "]";
try {
net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
cBldr.setBaseUrl(baseURL);
cBldr.setStartDatetimeMillis(sTime);
cBldr.setEndDatetimeMillis(eTime);
cBldr.addProperty("00010");
cBldr.addStationId(disIds[i]);
net.ooici.core.container.Container.Structure struct = AgentUtils.getUpdateInitStructure(GPBWrapper.Factory(cBldr.build()));
resp = runAgent(struct, AgentRunType.TEST_NO_WRITE);
} catch (Exception e) {
e.printStackTrace();
datasets.put(dsName + " (FAILED)", null);
continue;
}
Map<String, String> dsMeta = NcDumpParse.parseToMap(resp[0]);
datasets.put(dsName, dsMeta);
/* TODO: Eventually we can make this loop external and perform a sort beforehand.
* this sort would frontload attributes which are found more frequently
* across multiple datasets
*/
for (String key : dsMeta.keySet()) {
if (!metaLookup.contains(key)) {
metaLookup.add(key);
}
}
}
/** Write the CSV output */
String NEW_LINE = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
/* TODO: Step 1: add header data here */
sb.append("Dataset Name");
for (String metaName : metaLookup) {
sb.append("|");
sb.append(metaName);
// sb.append('"');
// sb.append(metaName.replaceAll(Pattern.quote("\""), "\"\""));
// sb.append('"');
}
/* Step 2: Add each row of data */
for (String ds : datasets.keySet()) {
Map<String, String> dsMeta = datasets.get(ds);
sb.append(NEW_LINE);
sb.append(ds);
// sb.append('"');
// sb.append(ds.replaceAll(Pattern.quote("\""), "\"\""));
// sb.append('"');
String metaValue = null;
for (String metaName : metaLookup) {
sb.append("|");
if (null != dsMeta && null != (metaValue = dsMeta.get(metaName))) {
sb.append(metaValue);
/* To ensure correct formatting, change all existing double quotes
* to two double quotes, and surround the whole cell value with
* double quotes...
*/
// sb.append('"');
// sb.append(metaValue.replaceAll(Pattern.quote("\""), "\"\""));
// sb.append('"');
}
}
}
System.out.println(NEW_LINE + NEW_LINE + "********************************************************");
System.out.println(sb.toString());
System.out.println(NEW_LINE + "********************************************************");
}
private static void generateRutgersSamples(boolean dailyValues) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date now = new Date();
try {
now = AgentUtils.ISO8601_DATE_FORMAT.parse("2011-04-29T00:00:00Z");
} catch (ParseException ex) {
throw new IOException("Error parsing time string", ex);
}
/* Generates samples for near-realtime high-resolution data */
String baseURL = "http://waterservices.usgs.gov/nwis/iv?";
long sTime = now.getTime() - 2592000000l;//start 30 days before
long eTime = now.getTime();
if (dailyValues) {
/* Generates samples for "historical" low-resolution data */
baseURL = "http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?";
try {
sTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2010-01-01T00:00:00Z").getTime();
} catch (ParseException ex) {
throw new IOException("Error parsing time string", ex);
}
}
String[] disIds = new String[]{"01184000", "01327750", "01357500", "01389500", "01403060", "01463500", "01578310", "01646500", "01592500", "01668000", "01491000", "02035000", "02041650", "01673000", "01674500"};
// String[] disNames = new String[]{"Connecticut", "Hudson", "Mohawk", "Passaic", "Raritan", "Delaware", "Susquehanna", "Potomac", "Patuxent", "Rappahannock", "Choptank", "James", "Appomattox", "Pamunkey", "Mattaponi"};
String[] tempIds = new String[]{"01362500", "01463500", "01646500"};
// String[] tempNames = new String[]{"Hudson", "Delware", "Potomac"};
String[] allIds = new String[]{"01184000", "01327750", "01357500", "01362500", "01389500", "01403060", "01463500", "01578310", "01646500", "01592500", "01668000", "01491000", "02035000", "02041650", "01673000", "01674500"};
for (int i = 0; i < allIds.length; i++) {
net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
cBldr.setBaseUrl(baseURL);
cBldr.setStartDatetimeMillis(sTime);
cBldr.setEndDatetimeMillis(eTime);
cBldr.addProperty("00010").addProperty("00060").addProperty("00065").addProperty("00045").addProperty("00095");
cBldr.addStationId(allIds[i]);
net.ooici.core.container.Container.Structure struct = AgentUtils.getUpdateInitStructure(GPBWrapper.Factory(cBldr.build()));
String[] res = runAgent(struct, AgentRunType.TEST_WRITE_NC);
// String[] res = runAgent(struct, AgentRunType.TEST_WRITE_OOICDM);
}
// for (int i = 0; i < disIds.length; i++) {
// net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
// cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
// cBldr.setBaseUrl(baseURL);
// cBldr.setStartTime(sTime);
// cBldr.setEndTime(eTime);
// cBldr.addProperty("00060");
// cBldr.addStationId(disIds[i]);
// String[] res = runAgent(cBldr.build(), AgentRunType.TEST_WRITE_NC);
//// NetcdfDataset dsout = null;
//// try {
//// dsout = NetcdfDataset.openDataset("ooici:" + res[0]);
//// ucar.nc2.FileWriter.writeToFile(dsout, output_prefix + disNames[i] + "_discharge.nc");
//// } catch (IOException ex) {
//// log.error("Error writing netcdf file", ex);
//// } finally {
//// if (dsout != null) {
//// dsout.close();
//// }
//// }
// }
//
// for (int i = 0; i < tempIds.length; i++) {
// net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
// cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
// cBldr.setBaseUrl(baseURL);
// cBldr.setStartTime(sTime);
// cBldr.setEndTime(eTime);
// cBldr.addProperty("00010");
// cBldr.addStationId(tempIds[i]);
// String[] res = runAgent(cBldr.build(), AgentRunType.TEST_WRITE_NC);
//// NetcdfDataset dsout = null;
//// try {
//// dsout = NetcdfDataset.openDataset("ooici:" + res[0]);
//// ucar.nc2.FileWriter.writeToFile(dsout, output_prefix + tempNames[i] + "_temp.nc");
//// } catch (IOException ex) {
//// log.error("Error writing netcdf file", ex);
//// } finally {
//// if (dsout != null) {
//// dsout.close();
//// }
//// }
// }
System.out.println("******FINISHED******");
}
private static void generateUHSamples(boolean dailyValues) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date now = new Date();
/* Generates samples for near-realtime high-resolution data */
String baseURL = "http://waterservices.usgs.gov/nwis/iv?";
long sTime = now.getTime() - 86400000;//start 1 day before
long eTime = now.getTime();
if (dailyValues) {
/* Generates samples for "historical" low-resolution data */
baseURL = "http://interim.waterservices.usgs.gov/NWISQuery/GetDV1?";
try {
sTime = AgentUtils.ISO8601_DATE_FORMAT.parse("2010-01-01T00:00:00Z").getTime();
} catch (ParseException ex) {
throw new IOException("Error parsing time string", ex);
}
}
String[] allIds = new String[]{"16211600", "16212800", "16213000", "16226200", "16226400", "16229000", "16238000", "16240500", "16242500", "16244000", "16247100", "211747157485601", "212359157502601", "212428157511201"};
for (int i = 0; i < allIds.length; i++) {
net.ooici.services.sa.DataSource.EoiDataContextMessage.Builder cBldr = net.ooici.services.sa.DataSource.EoiDataContextMessage.newBuilder();
cBldr.setSourceType(net.ooici.services.sa.DataSource.SourceType.USGS);
cBldr.setBaseUrl(baseURL);
cBldr.setStartDatetimeMillis(sTime);
cBldr.setEndDatetimeMillis(eTime);
cBldr.addProperty("00010").addProperty("00060").addProperty("00065").addProperty("00045").addProperty("00095");
cBldr.addStationId(allIds[i]);
net.ooici.core.container.Container.Structure struct = AgentUtils.getUpdateInitStructure(GPBWrapper.Factory(cBldr.build()));
// String[] res = runAgent(struct, AgentRunType.TEST_WRITE_NC);
String[] res = runAgent(struct, AgentRunType.TEST_WRITE_OOICDM);
}
System.out.println("******FINISHED******");
}
private static String[] runAgent(net.ooici.core.container.Container.Structure struct, AgentRunType agentRunType) throws IOException {
net.ooici.eoi.datasetagent.IDatasetAgent agent = net.ooici.eoi.datasetagent.AgentFactory.getDatasetAgent(net.ooici.services.sa.DataSource.SourceType.USGS);
agent.setAgentRunType(agentRunType);
java.util.HashMap<String, String> connInfo = null;
try {
connInfo = IonUtils.parseProperties();
} catch (IOException ex) {
log.error("Error parsing \"ooici-conn.properties\" cannot continue.", ex);
System.exit(1);
}
String[] result = agent.doUpdate(struct, connInfo);
log.debug("Response:");
for (String s : result) {
log.debug(s);
}
return result;
}
}
| true | true | public IObservationGroup wsDV_parseObservations(Reader rdr) {
/* TODO: Fix exception handling in this method, it is too generic; try/catch blocks should be as confined as possible */
/** XPATH queries */
final String XPATH_ELEMENT_TIME_SERIES = ".//ns1:timeSeries";
final String XPATH_ELEMENT_SITE_CODE = "./ns1:sourceInfo/ns1:siteCode";
final String XPATH_ATTRIBUTE_AGENCY_CODE = "./ns1:sourceInfo/ns1:siteCode/@agencyCode";
final String XPATH_ELEMENT_LATITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:latitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_LONGITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:longitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_VALUES = "./ns1:values";
final String XPATH_ELEMENT_VALUE = "./ns1:value";
final String XPATH_ELEMENT_VARIABLE_CODE = "./ns1:variable/ns1:variableCode";
final String XPATH_ELEMENT_VARIABLE_NAME = "./ns1:variable/ns1:variableName";
final String XPATH_ELEMENT_VARIABLE_NaN_VALUE = "./ns1:variable/ns1:noDataValue";
final String XPATH_ATTRIBUTE_QUALIFIERS = "./@qualifiers";
final String XPATH_ATTRIBUTE_DATETIME = "./@dateTime";
IObservationGroup obs = null;
SAXBuilder builder = new SAXBuilder();
Document doc = null;
String datetime = "[no date information]"; /* datetime defined here (outside try) for error reporting */
try {
doc = builder.build(rdr);
/** Grab Global Attributes (to be copied into each observation group */
Namespace ns1 = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.1/");
// Namespace ns2 = Namespace.getNamespace("ns2", "http://waterservices.usgs.gov/WaterML-1.1.xsd");
// Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema");
Element root = doc.getRootElement();
Element queryInfo = root.getChild("queryInfo", ns1);
Map<String, String> globalAttributes = new HashMap<String, String>();
/* Extract the Global Attributes */
/* title */
String queryUrl = xpathSafeSelectValue(queryInfo, ".//ns2:queryURL", null);
// globalAttributes.put("title", "USGS rivers data timeseries. Requested from \"" + queryUrl + "\"");
String siteName = xpathSafeSelectValue(root, "//ns1:sourceInfo/ns1:siteName", null);
String locationParam = xpathSafeSelectValue(root, "//ns1:queryInfo/ns1:criteria/ns1:locationParam", null);
locationParam = locationParam.substring(locationParam.indexOf(":") + 1, locationParam.indexOf("]"));
String variableName = xpathSafeSelectValue(root, "//ns1:variable/ns1:variableName", null);
int cut = variableName.indexOf(",");
if (cut >= 1) {
variableName = variableName.substring(0, cut);
}
String title = siteName + " (" + locationParam + ") - Daily Value";// + variableName;
title = title.replace(",", "").replace(".", "");
globalAttributes.put("title", title);
globalAttributes.put("institution", "USGS NWIS");
/* history */
globalAttributes.put("history", "Converted from WaterML1.1 to OOI CDM by " + UsgsAgent.class.getName());
/* references */
globalAttributes.put("references", "http://waterservices.usgs.gov/rest/DV-Service.html");
/* source */
globalAttributes.put("source", "Instantaneous Values Webservice (http://waterservices.usgs.gov/mwis/dv?)");
/* conventions - from schema */
// globalAttributes.put("Conventions", "CF-1.5");
/* Data URL */
/* CAN'T have this because it changes every update and we don't have a way of merging attributes across multiple updates */
// globalAttributes.put("data_url", data_url);
/** Get a list of provided time series */
List<?> timeseriesList = XPath.selectNodes(doc, XPATH_ELEMENT_TIME_SERIES);
/** Build an observation group for each unique sitecode */
Object nextTimeseries = null;
Iterator<?> iterTimeseries = timeseriesList.iterator();
boolean hasWaterSurface;
while (iterTimeseries.hasNext()) {
hasWaterSurface = false;
/* Grab the next element */
nextTimeseries = iterTimeseries.next();
if (null == nextTimeseries) {
continue;
}
/** Grab data for the current site */
String stnId = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_SITE_CODE)).getTextTrim();
String latitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LATITUDE)).getTextTrim();
String longitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LONGITUDE)).getTextTrim();
String noDataString = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_NaN_VALUE)).getTextTrim();
float lat = Float.parseFloat(latitude);
float lon = Float.parseFloat(longitude);
// float noDataValue = Float.parseFloat(noDataString);
/* Check to see if the observation group already exists */
if (obs == null) {
/* Create a new observation group if one does not currently exist */
obs = new ObservationGroupImpl(getNextGroupId(), stnId, lat, lon);
}
/** Grab variable data */
String variableCode = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_CODE)).getTextTrim();
// String variableUnits = getUnitsForVariableCode(variableCode);
// String variableName = getStdNameForVariableCode(variableCode);
VariableParams name = getDataNameForVariableCode(variableCode);
/* Check to see if this is the waterSurface var */
hasWaterSurface = (!hasWaterSurface) ? name == VariableParams.StandardVariable.RIVER_WATER_SURFACE_HEIGHT.getVariableParams() : hasWaterSurface;
/* May be multiple sets of values for a "variable" (i.e. middle, bottom, surface) */
List<?> valuesList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUES);
Iterator<?> valuesIter = valuesList.iterator();
Object valuesSet = null;
Pattern pattern = Pattern.compile("\\((.*)\\)");
Matcher match = null;
while (valuesIter.hasNext()) {
String varNameSuffix = "";
String longNameSuffix = "";
valuesSet = valuesIter.next();
if (valuesSet == null) {
continue;
}
Object method = XPath.selectSingleNode(valuesSet, "./ns1:method/ns1:methodDescription");
if (method != null) {
String methString = ((Element) method).getTextTrim();
if (methString != null & !methString.isEmpty()) {
longNameSuffix = methString;
match = pattern.matcher(methString);
if(match.find()) {
varNameSuffix = match.group(1);
} else {
varNameSuffix = methString;
}
varNameSuffix = varNameSuffix.toLowerCase().replace(" ", "_");
// varNameSuffix = methString.substring(methString.indexOf("(") + 1, methString.indexOf(")"));
}
}
// }
/** Add each timeseries value (observation) to the observation group */
/* Get a list of each observation */
// List<?> observationList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUE);
List<?> observationList = XPath.selectNodes(valuesSet, XPATH_ELEMENT_VALUE);
/* Add an observation for each "value" parsed */
Object next = null;
Iterator<?> iter = observationList.iterator();
while (iter.hasNext()) {
/* Grab the next element */
next = iter.next();
if (null == next) {
continue;
}
/* Grab observation data */
String qualifier = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_QUALIFIERS)).getValue();
datetime = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_DATETIME)).getValue();
String value = ((Element) next).getTextTrim();
// datetime = datetime.replaceAll("\\:", "").concat("Z");
/* Convert observation data */
int time = 0;
float data = 0;
float dpth = 0;
time = (int) (inSdf.parse(datetime).getTime() * 0.001);
// data = Float.parseFloat(value);
/* DON'T EVER CONVERT - Only convert data if we are dealing with Steamflow */
// if (name == VariableParams.RIVER_STREAMFLOW) {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value) * CONVERT_FT3_TO_M3); /* convert from (f3 s-1) --> (m3 s-1) */
// } else {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
// }
data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
dpth = 0;
/* Add the observation data */
// obs.addObservation(time, dpth, data, new VariableParams(name, DataType.FLOAT));
String vName = (!varNameSuffix.isEmpty()) ? name.getShortName().concat("_").concat(varNameSuffix) : name.getShortName();
String lName = (!longNameSuffix.isEmpty()) ? name.getDescription().concat(" ").concat(longNameSuffix) : name.getDescription();
obs.addObservation(time, dpth, data, new VariableParams(name.getStandardName(), vName, lName, name.getUnits(), DataType.FLOAT));
/* Add the data observation qualifier */
byte qualifier_value = Qualifier.getByteValue(qualifier.toString());
obs.addObservation(time, dpth, qualifier_value, new VariableParams(StandardVariable.USGS_QC_FLAG, DataType.BYTE));
}
}
/* If the group has waterSurface, add a the datum variable */
if (hasWaterSurface) {
obs.addScalarVariable(new VariableParams(VariableParams.StandardVariable.RIVER_WATER_SURFACE_REF_DATUM_ALTITUDE, DataType.FLOAT), 0f);
}
}
obs.addAttributes(globalAttributes);
} catch (JDOMException ex) {
log.error("Error while parsing xml from the given reader", ex);
} catch (IOException ex) {
log.error("General IO exception. Please see stack-trace", ex);
} catch (ParseException ex) {
log.error("Could not parse date information from XML result for: " + datetime, ex);
}
return obs;
}
| public IObservationGroup wsDV_parseObservations(Reader rdr) {
/* TODO: Fix exception handling in this method, it is too generic; try/catch blocks should be as confined as possible */
/** XPATH queries */
final String XPATH_ELEMENT_TIME_SERIES = ".//ns1:timeSeries";
final String XPATH_ELEMENT_SITE_CODE = "./ns1:sourceInfo/ns1:siteCode";
final String XPATH_ATTRIBUTE_AGENCY_CODE = "./ns1:sourceInfo/ns1:siteCode/@agencyCode";
final String XPATH_ELEMENT_LATITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:latitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_LONGITUDE = "./ns1:sourceInfo/ns1:geoLocation/ns1:geogLocation/ns1:longitude"; /* NOTE: geogLocation is (1..*) */
final String XPATH_ELEMENT_VALUES = "./ns1:values";
final String XPATH_ELEMENT_VALUE = "./ns1:value";
final String XPATH_ELEMENT_VARIABLE_CODE = "./ns1:variable/ns1:variableCode";
final String XPATH_ELEMENT_VARIABLE_NAME = "./ns1:variable/ns1:variableName";
final String XPATH_ELEMENT_VARIABLE_NaN_VALUE = "./ns1:variable/ns1:noDataValue";
final String XPATH_ATTRIBUTE_QUALIFIERS = "./@qualifiers";
final String XPATH_ATTRIBUTE_DATETIME = "./@dateTime";
IObservationGroup obs = null;
SAXBuilder builder = new SAXBuilder();
Document doc = null;
String datetime = "[no date information]"; /* datetime defined here (outside try) for error reporting */
try {
doc = builder.build(rdr);
/** Grab Global Attributes (to be copied into each observation group */
Namespace ns1 = Namespace.getNamespace("ns1", "http://www.cuahsi.org/waterML/1.1/");
// Namespace ns2 = Namespace.getNamespace("ns2", "http://waterservices.usgs.gov/WaterML-1.1.xsd");
// Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema");
Element root = doc.getRootElement();
Element queryInfo = root.getChild("queryInfo", ns1);
Map<String, String> globalAttributes = new HashMap<String, String>();
/* Extract the Global Attributes */
/* title */
String queryUrl = xpathSafeSelectValue(queryInfo, ".//ns2:queryURL", null);
// globalAttributes.put("title", "USGS rivers data timeseries. Requested from \"" + queryUrl + "\"");
String siteName = xpathSafeSelectValue(root, "//ns1:sourceInfo/ns1:siteName", null);
String locationParam = xpathSafeSelectValue(root, "//ns1:queryInfo/ns1:criteria/ns1:locationParam", null);
locationParam = locationParam.substring(locationParam.indexOf(":") + 1, locationParam.indexOf("]"));
String variableName = xpathSafeSelectValue(root, "//ns1:variable/ns1:variableName", null);
int cut = variableName.indexOf(",");
if (cut >= 1) {
variableName = variableName.substring(0, cut);
}
String title = siteName + " (" + locationParam + ") - Daily Value";// + variableName;
title = title.replace(",", "").replace(".", "");
globalAttributes.put("title", title);
globalAttributes.put("institution", "USGS NWIS");
/* history */
globalAttributes.put("history", "Converted from WaterML1.1 to OOI CDM by " + UsgsAgent.class.getName());
/* references */
globalAttributes.put("references", "http://waterservices.usgs.gov/rest/DV-Service.html");
/* source */
globalAttributes.put("source", "Daily Values Webservice (http://waterservices.usgs.gov/mwis/dv?)");
/* conventions - from schema */
// globalAttributes.put("Conventions", "CF-1.5");
/* Data URL */
/* CAN'T have this because it changes every update and we don't have a way of merging attributes across multiple updates */
// globalAttributes.put("data_url", data_url);
/** Get a list of provided time series */
List<?> timeseriesList = XPath.selectNodes(doc, XPATH_ELEMENT_TIME_SERIES);
/** Build an observation group for each unique sitecode */
Object nextTimeseries = null;
Iterator<?> iterTimeseries = timeseriesList.iterator();
boolean hasWaterSurface;
while (iterTimeseries.hasNext()) {
hasWaterSurface = false;
/* Grab the next element */
nextTimeseries = iterTimeseries.next();
if (null == nextTimeseries) {
continue;
}
/** Grab data for the current site */
String stnId = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_SITE_CODE)).getTextTrim();
String latitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LATITUDE)).getTextTrim();
String longitude = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_LONGITUDE)).getTextTrim();
String noDataString = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_NaN_VALUE)).getTextTrim();
float lat = Float.parseFloat(latitude);
float lon = Float.parseFloat(longitude);
// float noDataValue = Float.parseFloat(noDataString);
/* Check to see if the observation group already exists */
if (obs == null) {
/* Create a new observation group if one does not currently exist */
obs = new ObservationGroupImpl(getNextGroupId(), stnId, lat, lon);
}
/** Grab variable data */
String variableCode = ((Element) XPath.selectSingleNode(nextTimeseries, XPATH_ELEMENT_VARIABLE_CODE)).getTextTrim();
// String variableUnits = getUnitsForVariableCode(variableCode);
// String variableName = getStdNameForVariableCode(variableCode);
VariableParams name = getDataNameForVariableCode(variableCode);
/* Check to see if this is the waterSurface var */
hasWaterSurface = (!hasWaterSurface) ? name == VariableParams.StandardVariable.RIVER_WATER_SURFACE_HEIGHT.getVariableParams() : hasWaterSurface;
/* May be multiple sets of values for a "variable" (i.e. middle, bottom, surface) */
List<?> valuesList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUES);
Iterator<?> valuesIter = valuesList.iterator();
Object valuesSet = null;
Pattern pattern = Pattern.compile("\\((.*)\\)");
Matcher match = null;
while (valuesIter.hasNext()) {
String varNameSuffix = "";
String longNameSuffix = "";
valuesSet = valuesIter.next();
if (valuesSet == null) {
continue;
}
Object method = XPath.selectSingleNode(valuesSet, "./ns1:method/ns1:methodDescription");
if (method != null) {
String methString = ((Element) method).getTextTrim();
if (methString != null & !methString.isEmpty()) {
longNameSuffix = methString;
match = pattern.matcher(methString);
if(match.find()) {
varNameSuffix = match.group(1);
} else {
varNameSuffix = methString;
}
varNameSuffix = varNameSuffix.toLowerCase().replace(" ", "_");
// varNameSuffix = methString.substring(methString.indexOf("(") + 1, methString.indexOf(")"));
}
}
// }
/** Add each timeseries value (observation) to the observation group */
/* Get a list of each observation */
// List<?> observationList = XPath.selectNodes(nextTimeseries, XPATH_ELEMENT_VALUE);
List<?> observationList = XPath.selectNodes(valuesSet, XPATH_ELEMENT_VALUE);
/* Add an observation for each "value" parsed */
Object next = null;
Iterator<?> iter = observationList.iterator();
while (iter.hasNext()) {
/* Grab the next element */
next = iter.next();
if (null == next) {
continue;
}
/* Grab observation data */
String qualifier = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_QUALIFIERS)).getValue();
datetime = ((org.jdom.Attribute) XPath.selectSingleNode(next, XPATH_ATTRIBUTE_DATETIME)).getValue();
String value = ((Element) next).getTextTrim();
// datetime = datetime.replaceAll("\\:", "").concat("Z");
/* Convert observation data */
int time = 0;
float data = 0;
float dpth = 0;
time = (int) (inSdf.parse(datetime).getTime() * 0.001);
// data = Float.parseFloat(value);
/* DON'T EVER CONVERT - Only convert data if we are dealing with Steamflow */
// if (name == VariableParams.RIVER_STREAMFLOW) {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value) * CONVERT_FT3_TO_M3); /* convert from (f3 s-1) --> (m3 s-1) */
// } else {
// data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
// }
data = (noDataString.equals(value)) ? (Float.NaN) : (float) (Double.parseDouble(value));
dpth = 0;
/* Add the observation data */
// obs.addObservation(time, dpth, data, new VariableParams(name, DataType.FLOAT));
String vName = (!varNameSuffix.isEmpty()) ? name.getShortName().concat("_").concat(varNameSuffix) : name.getShortName();
String lName = (!longNameSuffix.isEmpty()) ? name.getDescription().concat(" ").concat(longNameSuffix) : name.getDescription();
obs.addObservation(time, dpth, data, new VariableParams(name.getStandardName(), vName, lName, name.getUnits(), DataType.FLOAT));
/* Add the data observation qualifier */
byte qualifier_value = Qualifier.getByteValue(qualifier.toString());
obs.addObservation(time, dpth, qualifier_value, new VariableParams(StandardVariable.USGS_QC_FLAG, DataType.BYTE));
}
}
/* If the group has waterSurface, add a the datum variable */
if (hasWaterSurface) {
obs.addScalarVariable(new VariableParams(VariableParams.StandardVariable.RIVER_WATER_SURFACE_REF_DATUM_ALTITUDE, DataType.FLOAT), 0f);
}
}
obs.addAttributes(globalAttributes);
} catch (JDOMException ex) {
log.error("Error while parsing xml from the given reader", ex);
} catch (IOException ex) {
log.error("General IO exception. Please see stack-trace", ex);
} catch (ParseException ex) {
log.error("Could not parse date information from XML result for: " + datetime, ex);
}
return obs;
}
|
diff --git a/src/main/java/org/jvnet/hudson/plugins/DownstreamBuildViewUpdateListener.java b/src/main/java/org/jvnet/hudson/plugins/DownstreamBuildViewUpdateListener.java
index 7fba3be..121ea79 100644
--- a/src/main/java/org/jvnet/hudson/plugins/DownstreamBuildViewUpdateListener.java
+++ b/src/main/java/org/jvnet/hudson/plugins/DownstreamBuildViewUpdateListener.java
@@ -1,118 +1,121 @@
/*
* The MIT License
*
* Copyright (c) 2009, Ushus Technologies LTD.,Shinod K Mohandas
*
* 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.jvnet.hudson.plugins;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.Cause.UpstreamCause;
import hudson.model.listeners.RunListener;
import hudson.XmlFile;
import hudson.BulkChange;
import hudson.model.*;
import hudson.model.listeners.SaveableListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.Logger;
/**
* This listener Updtes all build number {@link DownstreamBuildViewAction} to every new build.
*
* @author Shinod.Mohandas
*/
@SuppressWarnings("unchecked")
@Extension
public final class DownstreamBuildViewUpdateListener extends RunListener<AbstractBuild> implements Saveable{
/** The Logger. */
private static final Logger LOG = Logger.getLogger(DownstreamBuildViewUpdateListener.class.getName());
/**
* {@link Extension} needs parameterless constructor.
*/
public DownstreamBuildViewUpdateListener() {
super(AbstractBuild.class);
}
private AbstractBuild<?, ?> build;
/**
* {@inheritDoc}
*
* Adds {@link DownstreamBuildViewAction} to the build. Do this in <tt>onCompleted</tt>
* affected.
*/
@Override
public void onStarted(AbstractBuild r,TaskListener listener) {
//build = r;
CauseAction ca = r.getAction(CauseAction.class);
if (ca == null || ca.getCauses() ==null) {
return;
}
for (Cause c : ca.getCauses()){
if( c instanceof UpstreamCause){
UpstreamCause upcause = (UpstreamCause)c;
String upProjectName = upcause.getUpstreamProject();
int buildNumber = upcause.getUpstreamBuild();
AbstractProject project = Hudson.getInstance().getItemByFullName(upProjectName, AbstractProject.class);
+ // This can be null if this project was started by a non-project (ie, promotion action)
+ if (project == null) continue;
AbstractBuild upBuild = (AbstractBuild)project.getBuildByNumber(buildNumber);
+ if (upBuild == null) continue;
build = upBuild;
for (DownstreamBuildViewAction action : upBuild.getActions(DownstreamBuildViewAction.class)) {
action.addDownstreamBuilds(r.getProject().getName(),r.getNumber());
}
super.onFinalized(build);
save();
}
}
}
public synchronized void save() {
if(BulkChange.contains(this)) {
return;
}
try {
getConfigFile().write(build);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOG.info("Failed to save ");
}
}
private XmlFile getConfigFile() {
Run r= (Run)build;
return new XmlFile(r.XSTREAM,new File(r.getRootDir(),"build.xml" ));
}
}
| false | true | public void onStarted(AbstractBuild r,TaskListener listener) {
//build = r;
CauseAction ca = r.getAction(CauseAction.class);
if (ca == null || ca.getCauses() ==null) {
return;
}
for (Cause c : ca.getCauses()){
if( c instanceof UpstreamCause){
UpstreamCause upcause = (UpstreamCause)c;
String upProjectName = upcause.getUpstreamProject();
int buildNumber = upcause.getUpstreamBuild();
AbstractProject project = Hudson.getInstance().getItemByFullName(upProjectName, AbstractProject.class);
AbstractBuild upBuild = (AbstractBuild)project.getBuildByNumber(buildNumber);
build = upBuild;
for (DownstreamBuildViewAction action : upBuild.getActions(DownstreamBuildViewAction.class)) {
action.addDownstreamBuilds(r.getProject().getName(),r.getNumber());
}
super.onFinalized(build);
save();
}
}
}
| public void onStarted(AbstractBuild r,TaskListener listener) {
//build = r;
CauseAction ca = r.getAction(CauseAction.class);
if (ca == null || ca.getCauses() ==null) {
return;
}
for (Cause c : ca.getCauses()){
if( c instanceof UpstreamCause){
UpstreamCause upcause = (UpstreamCause)c;
String upProjectName = upcause.getUpstreamProject();
int buildNumber = upcause.getUpstreamBuild();
AbstractProject project = Hudson.getInstance().getItemByFullName(upProjectName, AbstractProject.class);
// This can be null if this project was started by a non-project (ie, promotion action)
if (project == null) continue;
AbstractBuild upBuild = (AbstractBuild)project.getBuildByNumber(buildNumber);
if (upBuild == null) continue;
build = upBuild;
for (DownstreamBuildViewAction action : upBuild.getActions(DownstreamBuildViewAction.class)) {
action.addDownstreamBuilds(r.getProject().getName(),r.getNumber());
}
super.onFinalized(build);
save();
}
}
}
|
diff --git a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/MirrorChooser.java b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/MirrorChooser.java
index a76d5d0b..4c2ec837 100644
--- a/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/MirrorChooser.java
+++ b/src/rapidshare/cz/vity/freerapid/plugins/services/rapidshare/MirrorChooser.java
@@ -1,108 +1,108 @@
package cz.vity.freerapid.plugins.services.rapidshare;
import cz.vity.freerapid.plugins.webclient.interfaces.ConfigurationStorageSupport;
import cz.vity.freerapid.plugins.webclient.interfaces.DialogSupport;
import cz.vity.freerapid.plugins.webclient.interfaces.PluginContext;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import java.util.logging.Logger;
import java.util.regex.Matcher;
class MirrorChooser {
final static String CONFIGFILE = "rapidMirror.xml";
private final static Logger logger = Logger.getLogger(MirrorChooser.class.getName());
private RapidShareMirrorConfig mirrorConfig;
private ConfigurationStorageSupport storage;
public void setContent(String content) {
this.content = content;
}
private String content;
private DialogSupport dialogSupport;
MirrorChooser(PluginContext context, RapidShareMirrorConfig mirrorConfig) {
storage = context.getConfigurationStorageSupport();
dialogSupport = context.getDialogSupport();
this.mirrorConfig = mirrorConfig;
}
private RapidShareMirrorConfig getMirrorConfig() {
return mirrorConfig;
}
MirrorBean getChosen() {
return mirrorConfig.getChosen();
}
private void setPreffered(Object object) {
if (object instanceof MirrorBean) {
MirrorBean mirror = (MirrorBean) object;
mirrorConfig.setChosen(mirror);
}
}
Object[] getArray() {
return mirrorConfig.getAr().toArray();
}
private void makeMirrorList() throws Exception {
logger.info("Making list of mirrors ");
mirrorConfig.getAr().add(MirrorBean.createDefault());
Matcher matcher = PlugUtils.matcher("<input (checked)? type=\"radio\" name=\"mirror\" onclick=\"document.dlf.action=.'http://rs[0-9]+([^.]+)[^']*.';\" /> ([^<]*)<br", content);
while (matcher.find()) {
String mirrorName = matcher.group(3);
String ident = matcher.group(2);
logger.info("Found mirror " + mirrorName + " ident " + ident);
mirrorConfig.getAr().add(new MirrorBean(mirrorName, ident));
}
- getMirrorConfig().setChosen(new MirrorBean());
+ getMirrorConfig().setChosen(MirrorBean.createDefault());
logger.info("Saving config ");
storage.storeConfigToFile(getMirrorConfig(), CONFIGFILE);
// <input checked type="radio" name="mirror" onclick="document.dlf.action=\'http://rs332gc.rapidshare.com/files/168531395/2434660/rkdr.part3.rar\';" /> GlobalCrossing<br />
}
void chooseFromList() throws Exception {
MirrorChooserUI ms = new MirrorChooserUI(this);
if (dialogSupport.showOKCancelDialog(ms, "Choose mirror")) {
setPreffered(ms.getChoosen());
logger.info("Setting chosen to " + getChosen());
storage.storeConfigToFile(getMirrorConfig(), CONFIGFILE);
}
}
private String findURL(String ident) {
if (ident.equals("default")) {
logger.info("Chosen is default, returning ");
return "";
}
Matcher matcher = PlugUtils.matcher("<input (checked)? type=\"radio\" name=\"mirror\" onclick=\"document.dlf.action=.'(http://rs[0-9]+" + ident + "[^']*).';\" />", content);
if (matcher.find()) {
String url = matcher.group(2);
logger.info("Found preferred url for ident " + ident + " " + url);
return url;
} else {
logger.info("URL for preferred mirror not found, returning default ");
return "";
}
}
public String getPreferredURL(String content) throws Exception {
this.content = content;
logger.info("Checking existing RapidShareMirrorConfig: " + storage.configFileExists(CONFIGFILE));
if (!storage.configFileExists(CONFIGFILE)) {
makeMirrorList();
}
return findURL(getChosen().getIdent());
}
}
| true | true | private void makeMirrorList() throws Exception {
logger.info("Making list of mirrors ");
mirrorConfig.getAr().add(MirrorBean.createDefault());
Matcher matcher = PlugUtils.matcher("<input (checked)? type=\"radio\" name=\"mirror\" onclick=\"document.dlf.action=.'http://rs[0-9]+([^.]+)[^']*.';\" /> ([^<]*)<br", content);
while (matcher.find()) {
String mirrorName = matcher.group(3);
String ident = matcher.group(2);
logger.info("Found mirror " + mirrorName + " ident " + ident);
mirrorConfig.getAr().add(new MirrorBean(mirrorName, ident));
}
getMirrorConfig().setChosen(new MirrorBean());
logger.info("Saving config ");
storage.storeConfigToFile(getMirrorConfig(), CONFIGFILE);
// <input checked type="radio" name="mirror" onclick="document.dlf.action=\'http://rs332gc.rapidshare.com/files/168531395/2434660/rkdr.part3.rar\';" /> GlobalCrossing<br />
}
| private void makeMirrorList() throws Exception {
logger.info("Making list of mirrors ");
mirrorConfig.getAr().add(MirrorBean.createDefault());
Matcher matcher = PlugUtils.matcher("<input (checked)? type=\"radio\" name=\"mirror\" onclick=\"document.dlf.action=.'http://rs[0-9]+([^.]+)[^']*.';\" /> ([^<]*)<br", content);
while (matcher.find()) {
String mirrorName = matcher.group(3);
String ident = matcher.group(2);
logger.info("Found mirror " + mirrorName + " ident " + ident);
mirrorConfig.getAr().add(new MirrorBean(mirrorName, ident));
}
getMirrorConfig().setChosen(MirrorBean.createDefault());
logger.info("Saving config ");
storage.storeConfigToFile(getMirrorConfig(), CONFIGFILE);
// <input checked type="radio" name="mirror" onclick="document.dlf.action=\'http://rs332gc.rapidshare.com/files/168531395/2434660/rkdr.part3.rar\';" /> GlobalCrossing<br />
}
|
diff --git a/api/src/main/java/org/openmrs/module/spreadsheetimport/SpreadsheetImportUtil.java b/api/src/main/java/org/openmrs/module/spreadsheetimport/SpreadsheetImportUtil.java
index 9b270c0..ccb809e 100644
--- a/api/src/main/java/org/openmrs/module/spreadsheetimport/SpreadsheetImportUtil.java
+++ b/api/src/main/java/org/openmrs/module/spreadsheetimport/SpreadsheetImportUtil.java
@@ -1,368 +1,369 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* 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.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.spreadsheetimport;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.ResultSet;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
/**
*
*/
public class SpreadsheetImportUtil {
/** Logger for this class and subclasses */
protected static final Log log = LogFactory.getLog(SpreadsheetImportUtil.class);
/**
* Resolve template dependencies: 1. Generate pre-specified values which are necessary for
* template to be imported. 2. Create import indices which describe the order in which columns
* must be imported. 3. Generated dependencies between columns being imported and other columns
* which be must imported first.
*
* @param template
* @throws Exception
*/
public static void resolveTemplateDependencies(SpreadsheetImportTemplate template) throws Exception {
Set<SpreadsheetImportTemplatePrespecifiedValue> prespecifiedValues = new TreeSet<SpreadsheetImportTemplatePrespecifiedValue>();
Map<String, Set<UniqueImport>> mapTnToUi = template.getMapOfColumnTablesToUniqueImportSet();
Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> mapUiToCs = template.getMapOfUniqueImportToColumnSet();
List<String> tableNamesSortedByImportIdx = new ArrayList<String>();
// // special treatment: when there's a reference to person_id, but
// // 1) the current table is not encounter and
// // 2) there's no column of table person to be added
// // then we should still add a person implicitly. This person record will use all default values
// boolean hasToAddPerson = false;
// for (UniqueImport key : mapUiToCs.keySet()) {
// String tableName = key.getTableName();
// if (!("encounter".equals(tableName) || mapTnToUi.keySet().contains("person"))) {
// hasToAddPerson = true;
// break;
// }
// }
// if (hasToAddPerson) {
// UniqueImport ui = new UniqueImport("person", new Integer(-1));
// mapTnToUi.put("person", new TreeSet<UniqueImport>());
// mapUiToCs.put(ui, new TreeSet<SpreadsheetImportTemplateColumn>());
// }
// Find requirements
for (UniqueImport key : mapUiToCs.keySet()) {
String tableName = key.getTableName();
Map<String, String> mapIkTnToCn = DatabaseBackend.getMapOfImportedKeyTableNameToColumnNamesForTable(tableName);
// encounter_id is optional, so it won't be part of mapIkTnToCn
// if we need to create new encounter for this row, then force it to be here
if (template.isEncounter() && "obs".equals(tableName))
mapIkTnToCn.put("encounter", "encounter_id");
// we need special treatment for provider_id of Encounter
// provider_id is of type person, but the meaning is different. During import, reference to person is considered patient,
// but for provider_id of Encounter, it refers to a health practitioner
if ("encounter".equals(tableName)) {
// mapIkTnToCn.put("person", "provider_id");
mapIkTnToCn.put("location", "location_id");
}
// Ignore users tableName
mapIkTnToCn.remove("users");
for (String necessaryTableName : mapIkTnToCn.keySet()) {
String necessaryColumnName = mapIkTnToCn.get(necessaryTableName);
// TODO: I believe patient and person are only tables with this relationship, if not, then this
// needs to be generalized
if (necessaryTableName.equals("patient") &&
!mapTnToUi.containsKey("patient") &&
mapTnToUi.containsKey("person")) {
necessaryTableName = "person";
}
if (mapTnToUi.containsKey(necessaryTableName) && !("encounter".equals(tableName) && ("provider_id".equals(necessaryColumnName)))) {
// Not already imported? Add
if (!tableNamesSortedByImportIdx.contains(necessaryTableName)) {
tableNamesSortedByImportIdx.add(necessaryTableName);
}
// Add column dependencies
// TODO: really _table_ dependencies - for simplicity only use _first_ column
// of each unique import
Set<SpreadsheetImportTemplateColumn> columnsImportFirst = new TreeSet<SpreadsheetImportTemplateColumn>();
for (UniqueImport uniqueImport : mapTnToUi.get(necessaryTableName)) {
// TODO: hacky cast
columnsImportFirst.add(((TreeSet<SpreadsheetImportTemplateColumn>)mapUiToCs.get(uniqueImport)).first());
}
for (SpreadsheetImportTemplateColumn columnImportNext : mapUiToCs.get(key)) {
for (SpreadsheetImportTemplateColumn columnImportFirst : columnsImportFirst) {
SpreadsheetImportTemplateColumnColumn cc = new SpreadsheetImportTemplateColumnColumn();
cc.setColumnImportFirst(columnImportFirst);
cc.setColumnImportNext(columnImportNext);
cc.setColumnName(necessaryColumnName);
columnImportNext.getColumnColumnsImportBefore().add(cc);
}
}
} else {
// Add pre-specified value
SpreadsheetImportTemplatePrespecifiedValue v = new SpreadsheetImportTemplatePrespecifiedValue();
v.setTemplate(template);
v.setTableDotColumn(necessaryTableName + "." + necessaryTableName + "_id");
for (SpreadsheetImportTemplateColumn column : mapUiToCs.get(key)) {
SpreadsheetImportTemplateColumnPrespecifiedValue cpv = new SpreadsheetImportTemplateColumnPrespecifiedValue();
cpv.setColumn(column);
cpv.setPrespecifiedValue(v);
// System.out.println("SpreadsheetImportUtils: " + v.getTableDotColumn() + " ==> " + v.getValue());
cpv.setColumnName(necessaryColumnName);
v.getColumnPrespecifiedValues().add(cpv);
}
prespecifiedValues.add(v);
}
}
// Add this tableName if not already added
if (!tableNamesSortedByImportIdx.contains(tableName)) {
tableNamesSortedByImportIdx.add(tableName);
}
}
// Add all pre-specified values
template.getPrespecifiedValues().addAll(prespecifiedValues);
// Set column import indices based on tableNameSortedByImportIdx
int importIdx = 0;
for (String tableName : tableNamesSortedByImportIdx) {
for (UniqueImport uniqueImport : mapTnToUi.get(tableName)) {
for (SpreadsheetImportTemplateColumn column : mapUiToCs.get(uniqueImport)) {
column.setImportIdx(importIdx);
importIdx++;
}
}
}
}
private static String toString(List<String> list) {
String result = "";
for (int i = 0; i < list.size(); i++) {
if (list.size() == 2 && i == 1) {
result += " and ";
} else if (list.size() > 2 && i == list.size() - 1) {
result += ", and ";
} else if (i != 0) {
result += ", ";
}
result += list.get(i);
}
return result;
}
public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName,
List<String> messages, boolean rollbackTransaction) throws Exception {
if (file.isEmpty()) {
messages.add("file must not be empty");
return null;
}
// Open file
Workbook wb = WorkbookFactory.create(file.getInputStream());
Sheet sheet;
if (!StringUtils.hasText(sheetName)) {
sheet = wb.getSheetAt(0);
} else {
sheet = wb.getSheet(sheetName);
}
// Header row
Row firstRow = sheet.getRow(0);
if (firstRow == null) {
messages.add("Spreadsheet header row must not be null");
return null;
}
List<String> columnNames = new Vector<String>();
for (Cell cell : firstRow) {
columnNames.add(cell.getStringCellValue());
}
if (log.isDebugEnabled()) {
log.debug("Column names: " + columnNames.toString());
}
// Required column names
List<String> columnNamesOnlyInTemplate = new Vector<String>();
columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList());
columnNamesOnlyInTemplate.removeAll(columnNames);
if (columnNamesOnlyInTemplate.isEmpty() == false) {
messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate));
return null;
}
// Extra column names?
List<String> columnNamesOnlyInSheet = new Vector<String>();
columnNamesOnlyInSheet.addAll(columnNames);
columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList());
if (columnNamesOnlyInSheet.isEmpty() == false) {
messages.add("Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet));
}
// Process rows
boolean skipThisRow = true;
for (Row row : sheet) {
if (skipThisRow == true) {
skipThisRow = false;
} else {
boolean rowHasData = false;
Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template
.getMapOfUniqueImportToColumnSetSortedByImportIdx();
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
Object value = null;
// check for empty cell (new Encounter)
if (cell == null) {
rowHasData = true;
column.setValue("");
continue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
value = new Boolean(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
value = new Byte(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
java.util.Date date = cell.getDateCellValue();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
value = "'" + sqlDate.toString() + "'";
} else {
value = cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
// Escape for SQL
value = "'" + cell.getRichStringCellValue() + "'";
break;
}
if (value != null) {
rowHasData = true;
column.setValue(value);
- }
+ } else
+ column.setValue("");
}
}
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if (isFirst) {
// Should be same for all columns in unique import
// System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size());
if (column.getColumnPrespecifiedValues().size() > 0) {
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
// System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue());
}
}
}
}
}
if (rowHasData) {
Exception exception = null;
try {
DatabaseBackend.validateData(rowData);
String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction);
if (encounterId != null) {
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("encounter".equals(column.getTableName())) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
if (cell == null)
cell = row.createCell(idx);
cell.setCellValue(encounterId);
}
}
}
}
} catch (SpreadsheetImportTemplateValidationException e) {
messages.add("Validation failed: " + e.getMessage());
return null;
} catch (SpreadsheetImportDuplicateValueException e) {
messages.add("found duplicate value for column " + e.getColumn().getName() + " with value " + e.getColumn().getValue());
return null;
} catch (SpreadsheetImportSQLSyntaxException e) {
messages.add("SQL syntax error: \"" + e.getSqlErrorMessage() + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\"");
return null;
} catch (Exception e) {
exception = e;
}
if (exception != null) {
throw exception;
}
}
}
}
// write back Excel file to a temp location
File returnFile = File.createTempFile("sim", ".xls");
FileOutputStream fos = new FileOutputStream(returnFile);
wb.write(fos);
fos.close();
return returnFile;
}
}
| true | true | public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName,
List<String> messages, boolean rollbackTransaction) throws Exception {
if (file.isEmpty()) {
messages.add("file must not be empty");
return null;
}
// Open file
Workbook wb = WorkbookFactory.create(file.getInputStream());
Sheet sheet;
if (!StringUtils.hasText(sheetName)) {
sheet = wb.getSheetAt(0);
} else {
sheet = wb.getSheet(sheetName);
}
// Header row
Row firstRow = sheet.getRow(0);
if (firstRow == null) {
messages.add("Spreadsheet header row must not be null");
return null;
}
List<String> columnNames = new Vector<String>();
for (Cell cell : firstRow) {
columnNames.add(cell.getStringCellValue());
}
if (log.isDebugEnabled()) {
log.debug("Column names: " + columnNames.toString());
}
// Required column names
List<String> columnNamesOnlyInTemplate = new Vector<String>();
columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList());
columnNamesOnlyInTemplate.removeAll(columnNames);
if (columnNamesOnlyInTemplate.isEmpty() == false) {
messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate));
return null;
}
// Extra column names?
List<String> columnNamesOnlyInSheet = new Vector<String>();
columnNamesOnlyInSheet.addAll(columnNames);
columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList());
if (columnNamesOnlyInSheet.isEmpty() == false) {
messages.add("Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet));
}
// Process rows
boolean skipThisRow = true;
for (Row row : sheet) {
if (skipThisRow == true) {
skipThisRow = false;
} else {
boolean rowHasData = false;
Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template
.getMapOfUniqueImportToColumnSetSortedByImportIdx();
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
Object value = null;
// check for empty cell (new Encounter)
if (cell == null) {
rowHasData = true;
column.setValue("");
continue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
value = new Boolean(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
value = new Byte(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
java.util.Date date = cell.getDateCellValue();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
value = "'" + sqlDate.toString() + "'";
} else {
value = cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
// Escape for SQL
value = "'" + cell.getRichStringCellValue() + "'";
break;
}
if (value != null) {
rowHasData = true;
column.setValue(value);
}
}
}
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if (isFirst) {
// Should be same for all columns in unique import
// System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size());
if (column.getColumnPrespecifiedValues().size() > 0) {
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
// System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue());
}
}
}
}
}
if (rowHasData) {
Exception exception = null;
try {
DatabaseBackend.validateData(rowData);
String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction);
if (encounterId != null) {
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("encounter".equals(column.getTableName())) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
if (cell == null)
cell = row.createCell(idx);
cell.setCellValue(encounterId);
}
}
}
}
} catch (SpreadsheetImportTemplateValidationException e) {
messages.add("Validation failed: " + e.getMessage());
return null;
} catch (SpreadsheetImportDuplicateValueException e) {
messages.add("found duplicate value for column " + e.getColumn().getName() + " with value " + e.getColumn().getValue());
return null;
} catch (SpreadsheetImportSQLSyntaxException e) {
messages.add("SQL syntax error: \"" + e.getSqlErrorMessage() + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\"");
return null;
} catch (Exception e) {
exception = e;
}
if (exception != null) {
throw exception;
}
}
}
}
// write back Excel file to a temp location
File returnFile = File.createTempFile("sim", ".xls");
FileOutputStream fos = new FileOutputStream(returnFile);
wb.write(fos);
fos.close();
return returnFile;
}
| public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName,
List<String> messages, boolean rollbackTransaction) throws Exception {
if (file.isEmpty()) {
messages.add("file must not be empty");
return null;
}
// Open file
Workbook wb = WorkbookFactory.create(file.getInputStream());
Sheet sheet;
if (!StringUtils.hasText(sheetName)) {
sheet = wb.getSheetAt(0);
} else {
sheet = wb.getSheet(sheetName);
}
// Header row
Row firstRow = sheet.getRow(0);
if (firstRow == null) {
messages.add("Spreadsheet header row must not be null");
return null;
}
List<String> columnNames = new Vector<String>();
for (Cell cell : firstRow) {
columnNames.add(cell.getStringCellValue());
}
if (log.isDebugEnabled()) {
log.debug("Column names: " + columnNames.toString());
}
// Required column names
List<String> columnNamesOnlyInTemplate = new Vector<String>();
columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList());
columnNamesOnlyInTemplate.removeAll(columnNames);
if (columnNamesOnlyInTemplate.isEmpty() == false) {
messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate));
return null;
}
// Extra column names?
List<String> columnNamesOnlyInSheet = new Vector<String>();
columnNamesOnlyInSheet.addAll(columnNames);
columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList());
if (columnNamesOnlyInSheet.isEmpty() == false) {
messages.add("Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet));
}
// Process rows
boolean skipThisRow = true;
for (Row row : sheet) {
if (skipThisRow == true) {
skipThisRow = false;
} else {
boolean rowHasData = false;
Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template
.getMapOfUniqueImportToColumnSetSortedByImportIdx();
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
Object value = null;
// check for empty cell (new Encounter)
if (cell == null) {
rowHasData = true;
column.setValue("");
continue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
value = new Boolean(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
value = new Byte(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
java.util.Date date = cell.getDateCellValue();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
value = "'" + sqlDate.toString() + "'";
} else {
value = cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
// Escape for SQL
value = "'" + cell.getRichStringCellValue() + "'";
break;
}
if (value != null) {
rowHasData = true;
column.setValue(value);
} else
column.setValue("");
}
}
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if (isFirst) {
// Should be same for all columns in unique import
// System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size());
if (column.getColumnPrespecifiedValues().size() > 0) {
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
// System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue());
}
}
}
}
}
if (rowHasData) {
Exception exception = null;
try {
DatabaseBackend.validateData(rowData);
String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction);
if (encounterId != null) {
for (UniqueImport uniqueImport : rowData.keySet()) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("encounter".equals(column.getTableName())) {
int idx = columnNames.indexOf(column.getName());
Cell cell = row.getCell(idx);
if (cell == null)
cell = row.createCell(idx);
cell.setCellValue(encounterId);
}
}
}
}
} catch (SpreadsheetImportTemplateValidationException e) {
messages.add("Validation failed: " + e.getMessage());
return null;
} catch (SpreadsheetImportDuplicateValueException e) {
messages.add("found duplicate value for column " + e.getColumn().getName() + " with value " + e.getColumn().getValue());
return null;
} catch (SpreadsheetImportSQLSyntaxException e) {
messages.add("SQL syntax error: \"" + e.getSqlErrorMessage() + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\"");
return null;
} catch (Exception e) {
exception = e;
}
if (exception != null) {
throw exception;
}
}
}
}
// write back Excel file to a temp location
File returnFile = File.createTempFile("sim", ".xls");
FileOutputStream fos = new FileOutputStream(returnFile);
wb.write(fos);
fos.close();
return returnFile;
}
|
diff --git a/contrib/src/main/java/com/datatorrent/contrib/summit/ads/BucketOperator.java b/contrib/src/main/java/com/datatorrent/contrib/summit/ads/BucketOperator.java
index d49d8ac04..6da5f4203 100644
--- a/contrib/src/main/java/com/datatorrent/contrib/summit/ads/BucketOperator.java
+++ b/contrib/src/main/java/com/datatorrent/contrib/summit/ads/BucketOperator.java
@@ -1,112 +1,112 @@
/*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.datatorrent.contrib.summit.ads;
import com.datatorrent.api.BaseOperator;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DAGContext;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.annotation.InputPortFieldAnnotation;
import com.datatorrent.api.annotation.OutputPortFieldAnnotation;
import com.datatorrent.lib.util.KeyValPair;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.mutable.MutableDouble;
/**
*
* @author Pramod Immaneni <[email protected]>
*/
public class BucketOperator extends BaseOperator
{
private long windowWidth;
private long currentWindowId;
private HashMap<AggrKey, Map<String, MutableDouble>> aggrMap;
@OutputPortFieldAnnotation(name = "outputPort", optional = false)
public final transient DefaultOutputPort<KeyValPair<AggrKey, Map<String, MutableDouble>>> outputPort = new DefaultOutputPort<KeyValPair<AggrKey, Map<String, MutableDouble>>>(this);
@Override
public void setup(OperatorContext context)
{
super.setup(context);
windowWidth = context.attrValue(DAGContext.STREAMING_WINDOW_SIZE_MILLIS, 500);
}
@Override
public void beginWindow(long windowId)
{
super.beginWindow(windowId);
currentWindowId = windowId;
aggrMap = new HashMap<AggrKey, Map<String, MutableDouble>>();
}
@Override
public void endWindow()
{
//outputPort.emit(aggrMap);
for (Map.Entry<AggrKey, Map<String, MutableDouble>> entry : aggrMap.entrySet()) {
//Map<AggrKey, Map<String, MutableDouble>> map = new HashMap<AggrKey, Map<String, MutableDouble>>();
//map.put(entry.getKey(), entry.getValue());
//outputPort.emit(map);
outputPort.emit(new KeyValPair<AggrKey,Map<String, MutableDouble>>(entry.getKey(), entry.getValue()));
}
}
@Override
public void teardown()
{
super.teardown(); //To change body of generated methods, choose Tools | Templates.
}
private long getTime() {
return (currentWindowId >>> 32) * 1000 + windowWidth * (currentWindowId & 0xffffffffL);
}
@InputPortFieldAnnotation(name = "inputPort", optional = false)
public transient DefaultInputPort<AdInfo> inputPort = new DefaultInputPort<AdInfo>(this) {
@Override
public void process(AdInfo tuple)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tuple.getTimestamp());
AggrKey aggrKey = new AggrKey(calendar,AggrKey.TIMESPEC_MINUTE_SPEC, tuple.getPublisherId(), tuple.getAdvertiserId(), tuple.getAdUnit());
Map<String, MutableDouble> map = aggrMap.get(aggrKey);
if (map == null) {
map = new HashMap<String, MutableDouble>();
aggrMap.put(aggrKey, map);
}
- if (tuple.isClick()) {
+ if (!tuple.isClick()) {
updateVal(map, "0", 1);
updateVal(map, "1", tuple.getValue());
updateVal(map, "2", 0.0);
updateVal(map, "3", 1);
updateVal(map, "4", 0);
} else {
updateVal(map, "0", 1);
updateVal(map, "1", 0.0);
updateVal(map, "2", tuple.getValue());
updateVal(map, "3", 0);
updateVal(map, "4", 1);
}
}
void updateVal(Map<String, MutableDouble> map, String key, Number val) {
MutableDouble cval = map.get(key);
if (cval == null) {
map.put(key, new MutableDouble(val));
}else {
cval.add(val);
}
}
};
}
| true | true | public void process(AdInfo tuple)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tuple.getTimestamp());
AggrKey aggrKey = new AggrKey(calendar,AggrKey.TIMESPEC_MINUTE_SPEC, tuple.getPublisherId(), tuple.getAdvertiserId(), tuple.getAdUnit());
Map<String, MutableDouble> map = aggrMap.get(aggrKey);
if (map == null) {
map = new HashMap<String, MutableDouble>();
aggrMap.put(aggrKey, map);
}
if (tuple.isClick()) {
updateVal(map, "0", 1);
updateVal(map, "1", tuple.getValue());
updateVal(map, "2", 0.0);
updateVal(map, "3", 1);
updateVal(map, "4", 0);
} else {
updateVal(map, "0", 1);
updateVal(map, "1", 0.0);
updateVal(map, "2", tuple.getValue());
updateVal(map, "3", 0);
updateVal(map, "4", 1);
}
}
| public void process(AdInfo tuple)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(tuple.getTimestamp());
AggrKey aggrKey = new AggrKey(calendar,AggrKey.TIMESPEC_MINUTE_SPEC, tuple.getPublisherId(), tuple.getAdvertiserId(), tuple.getAdUnit());
Map<String, MutableDouble> map = aggrMap.get(aggrKey);
if (map == null) {
map = new HashMap<String, MutableDouble>();
aggrMap.put(aggrKey, map);
}
if (!tuple.isClick()) {
updateVal(map, "0", 1);
updateVal(map, "1", tuple.getValue());
updateVal(map, "2", 0.0);
updateVal(map, "3", 1);
updateVal(map, "4", 0);
} else {
updateVal(map, "0", 1);
updateVal(map, "1", 0.0);
updateVal(map, "2", tuple.getValue());
updateVal(map, "3", 0);
updateVal(map, "4", 1);
}
}
|
diff --git a/Charm_Tree/src/net/sf/anathema/character/generic/framework/magic/stringbuilder/CharmKeywordsStringBuilder.java b/Charm_Tree/src/net/sf/anathema/character/generic/framework/magic/stringbuilder/CharmKeywordsStringBuilder.java
index 8a9496c5fc..998a38d71a 100644
--- a/Charm_Tree/src/net/sf/anathema/character/generic/framework/magic/stringbuilder/CharmKeywordsStringBuilder.java
+++ b/Charm_Tree/src/net/sf/anathema/character/generic/framework/magic/stringbuilder/CharmKeywordsStringBuilder.java
@@ -1,39 +1,39 @@
package net.sf.anathema.character.generic.framework.magic.stringbuilder;
import net.sf.anathema.character.generic.magic.ICharm;
import net.sf.anathema.character.generic.magic.IMagic;
import net.sf.anathema.character.generic.magic.charms.ICharmAttribute;
import net.sf.anathema.lib.resources.IResources;
public class CharmKeywordsStringBuilder implements IMagicTooltipStringBuilder
{
private final IResources resources;
public CharmKeywordsStringBuilder(IResources resources)
{
this.resources = resources;
}
@Override
public void buildStringForMagic(StringBuilder builder, IMagic magic, Object details) {
if (magic instanceof ICharm)
{
ICharm charm = (ICharm)magic;
StringBuilder listBuilder = new StringBuilder();
for (ICharmAttribute attribute : charm.getAttributes())
{
if (attribute.isVisualized()) {
if (listBuilder.length() != 0) {
listBuilder.append(CommaSpace);
}
listBuilder.append(resources.getString("Keyword." + attribute.getId())); //$NON-NLS-1$
}
- }
- if (builder.length() > 0) {
- listBuilder.insert(0, resources.getString("CharmTreeView.ToolTip.Keywords") + ColonSpace); //$NON-NLS-1$
- listBuilder.append(HtmlLineBreak);
+ }
+ if (listBuilder.length() > 0) {
+ listBuilder.insert(0, resources.getString("CharmTreeView.ToolTip.Keywords") + ColonSpace); //$NON-NLS-1$
+ listBuilder.append(HtmlLineBreak);
}
builder.append(listBuilder);
}
}
}
| true | true | public void buildStringForMagic(StringBuilder builder, IMagic magic, Object details) {
if (magic instanceof ICharm)
{
ICharm charm = (ICharm)magic;
StringBuilder listBuilder = new StringBuilder();
for (ICharmAttribute attribute : charm.getAttributes())
{
if (attribute.isVisualized()) {
if (listBuilder.length() != 0) {
listBuilder.append(CommaSpace);
}
listBuilder.append(resources.getString("Keyword." + attribute.getId())); //$NON-NLS-1$
}
}
if (builder.length() > 0) {
listBuilder.insert(0, resources.getString("CharmTreeView.ToolTip.Keywords") + ColonSpace); //$NON-NLS-1$
listBuilder.append(HtmlLineBreak);
}
builder.append(listBuilder);
}
}
| public void buildStringForMagic(StringBuilder builder, IMagic magic, Object details) {
if (magic instanceof ICharm)
{
ICharm charm = (ICharm)magic;
StringBuilder listBuilder = new StringBuilder();
for (ICharmAttribute attribute : charm.getAttributes())
{
if (attribute.isVisualized()) {
if (listBuilder.length() != 0) {
listBuilder.append(CommaSpace);
}
listBuilder.append(resources.getString("Keyword." + attribute.getId())); //$NON-NLS-1$
}
}
if (listBuilder.length() > 0) {
listBuilder.insert(0, resources.getString("CharmTreeView.ToolTip.Keywords") + ColonSpace); //$NON-NLS-1$
listBuilder.append(HtmlLineBreak);
}
builder.append(listBuilder);
}
}
|
diff --git a/12_testing/Initials.java b/12_testing/Initials.java
index 5f8c8e8..6c83791 100644
--- a/12_testing/Initials.java
+++ b/12_testing/Initials.java
@@ -1,16 +1,16 @@
public class Initials {
public static String getInitials(String fullName) {
String result = "";
- String[] words = fullName.split(" ");
+ String[] words = fullName.split("\\s+");
for (int i = 0; i < words.length; i++) {
String nextInitial = "" + words[i].charAt(0);
result = result + nextInitial.toUpperCase();
}
return result;
}
public static void main(String[] args) {
System.out.print("Enter full name: ");
String fullName = System.console().readLine();
System.out.println("initials: " + getInitials(fullName));
}
}
| true | true | public static String getInitials(String fullName) {
String result = "";
String[] words = fullName.split(" ");
for (int i = 0; i < words.length; i++) {
String nextInitial = "" + words[i].charAt(0);
result = result + nextInitial.toUpperCase();
}
return result;
}
| public static String getInitials(String fullName) {
String result = "";
String[] words = fullName.split("\\s+");
for (int i = 0; i < words.length; i++) {
String nextInitial = "" + words[i].charAt(0);
result = result + nextInitial.toUpperCase();
}
return result;
}
|
diff --git a/src/com/nadmm/airports/e6b/AltitudesFragment.java b/src/com/nadmm/airports/e6b/AltitudesFragment.java
index fcf0ae61..e430a829 100644
--- a/src/com/nadmm/airports/e6b/AltitudesFragment.java
+++ b/src/com/nadmm/airports/e6b/AltitudesFragment.java
@@ -1,116 +1,116 @@
/*
* FlightIntel for Pilots
*
* Copyright 2011-2013 Nadeem Hasan <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nadmm.airports.e6b;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.nadmm.airports.FragmentBase;
import com.nadmm.airports.ListMenuFragment;
import com.nadmm.airports.R;
public class AltitudesFragment extends FragmentBase {
private EditText mElevationEdit;
private EditText mAltimeterEdit;
private EditText mTemperatureEdit;
private EditText mPressureAltitudeEdit;
private EditText mDensityAltitudeEdit;
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged( CharSequence s, int start, int before, int count ) {
}
@Override
public void beforeTextChanged( CharSequence s, int start, int count, int after ) {
}
@Override
public void afterTextChanged( Editable s ) {
processInput();
}
};
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {
return inflate( R.layout.e6b_altimetry_altitude );
}
@Override
public void onActivityCreated( Bundle savedInstanceState ) {
super.onActivityCreated( savedInstanceState );
String title = getArguments().getString( ListMenuFragment.SUBTITLE_TEXT );
TextView label = (TextView) findViewById( R.id.e6b_label );
label.setText( title );
TextView msg = (TextView) findViewById( R.id.e6b_isa_msg );
msg.setText( "At sea level on a standard day, temperature is 15\u00B0C or 59\u00B0F" +
" and pressure is 29.92126 inHg or 1013.25 mB" );
mElevationEdit = (EditText) findViewById( R.id.e6b_elevation );
mAltimeterEdit = (EditText) findViewById( R.id.e6b_altimeter_in );
mTemperatureEdit = (EditText) findViewById( R.id.e6b_temperature_c );
mPressureAltitudeEdit = (EditText) findViewById( R.id.e6b_pressure_altitude );
mDensityAltitudeEdit = (EditText) findViewById( R.id.e6b_density_altitude );
mElevationEdit.addTextChangedListener( mTextWatcher );
mAltimeterEdit.addTextChangedListener( mTextWatcher );
mTemperatureEdit.addTextChangedListener( mTextWatcher );
}
private void processInput() {
long elevation = -1;
double altimeter = -1;
- double temperature = -1;
+ double temperatureC = -1;
try {
elevation = Long.valueOf( mElevationEdit.getText().toString() );
altimeter = Double.valueOf( mAltimeterEdit.getText().toString() );
- temperature = Double.valueOf( mTemperatureEdit.getText().toString() );
+ temperatureC = Double.valueOf( mTemperatureEdit.getText().toString() );
} catch ( NumberFormatException e ) {
}
- if ( elevation != -1 && altimeter != -1 ) {
+ if ( elevation != -1 && altimeter != -1 && temperatureC != -1 ) {
long delta = Math.round( 145442.2*( 1-Math.pow( altimeter/29.92126, 0.190261 ) ) );
long pressureAltitude = elevation+delta;
mPressureAltitudeEdit.setText( String.valueOf( pressureAltitude ) );
double stdTempK = 15.0-( 0.0019812*elevation )+273.15;
- double actTempK = temperature+273.15;
+ double actTempK = temperatureC+273.15;
long densityAltitude = Math.round( pressureAltitude
+( stdTempK/0.0019812 )*( 1-Math.pow( stdTempK/actTempK, 0.234969 ) ) );
mDensityAltitudeEdit.setText( String.valueOf( densityAltitude ) );
} else {
mPressureAltitudeEdit.setText( "" );
mDensityAltitudeEdit.setText( "" );
}
}
}
| false | true | private void processInput() {
long elevation = -1;
double altimeter = -1;
double temperature = -1;
try {
elevation = Long.valueOf( mElevationEdit.getText().toString() );
altimeter = Double.valueOf( mAltimeterEdit.getText().toString() );
temperature = Double.valueOf( mTemperatureEdit.getText().toString() );
} catch ( NumberFormatException e ) {
}
if ( elevation != -1 && altimeter != -1 ) {
long delta = Math.round( 145442.2*( 1-Math.pow( altimeter/29.92126, 0.190261 ) ) );
long pressureAltitude = elevation+delta;
mPressureAltitudeEdit.setText( String.valueOf( pressureAltitude ) );
double stdTempK = 15.0-( 0.0019812*elevation )+273.15;
double actTempK = temperature+273.15;
long densityAltitude = Math.round( pressureAltitude
+( stdTempK/0.0019812 )*( 1-Math.pow( stdTempK/actTempK, 0.234969 ) ) );
mDensityAltitudeEdit.setText( String.valueOf( densityAltitude ) );
} else {
mPressureAltitudeEdit.setText( "" );
mDensityAltitudeEdit.setText( "" );
}
}
| private void processInput() {
long elevation = -1;
double altimeter = -1;
double temperatureC = -1;
try {
elevation = Long.valueOf( mElevationEdit.getText().toString() );
altimeter = Double.valueOf( mAltimeterEdit.getText().toString() );
temperatureC = Double.valueOf( mTemperatureEdit.getText().toString() );
} catch ( NumberFormatException e ) {
}
if ( elevation != -1 && altimeter != -1 && temperatureC != -1 ) {
long delta = Math.round( 145442.2*( 1-Math.pow( altimeter/29.92126, 0.190261 ) ) );
long pressureAltitude = elevation+delta;
mPressureAltitudeEdit.setText( String.valueOf( pressureAltitude ) );
double stdTempK = 15.0-( 0.0019812*elevation )+273.15;
double actTempK = temperatureC+273.15;
long densityAltitude = Math.round( pressureAltitude
+( stdTempK/0.0019812 )*( 1-Math.pow( stdTempK/actTempK, 0.234969 ) ) );
mDensityAltitudeEdit.setText( String.valueOf( densityAltitude ) );
} else {
mPressureAltitudeEdit.setText( "" );
mDensityAltitudeEdit.setText( "" );
}
}
|
diff --git a/tds/src/main/java/thredds/servlet/ThreddsDefaultServlet.java b/tds/src/main/java/thredds/servlet/ThreddsDefaultServlet.java
index b3828c3a4..3227091ed 100644
--- a/tds/src/main/java/thredds/servlet/ThreddsDefaultServlet.java
+++ b/tds/src/main/java/thredds/servlet/ThreddsDefaultServlet.java
@@ -1,872 +1,873 @@
// $Id: ThreddsDefaultServlet.java 51 2006-07-12 17:13:13Z caron $
/*
* Copyright 1997-2006 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* [email protected].
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package thredds.servlet;
import org.apache.log4j.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ucar.nc2.util.DiskCache;
import ucar.nc2.util.DiskCache2;
import ucar.unidata.io.FileCache;
import ucar.nc2.NetcdfFileCache;
import ucar.nc2.ncml.Aggregation;
import ucar.nc2.ncml.AggregationFmrc;
import ucar.nc2.dataset.NetcdfDatasetCache;
import thredds.catalog.InvDatasetScan;
import thredds.catalog.InvCatalog;
import thredds.catalog.InvDataset;
import thredds.catalog.InvDatasetImpl;
/**
* THREDDS default servlet - handles everything not explicitly mapped.
* You should map this servlet to "/*" in web.xml.
* @author caron
* @version $Revision: 51 $ $Date: 2006-07-12 17:13:13Z $
*/
public class ThreddsDefaultServlet extends AbstractServlet {
static String version = null;
protected String getPath() { return ""; }
protected String getContextName() { return "THREDDS Data Server"; }
protected String getDocsPath() { return "http://www.unidata.ucar.edu/projects/THREDDS/tech/TDS.html"; }
//protected String getDocsPath() { return "docs/"; }
protected String getUserCssPath() { return "upc.css"; }
protected String getContextLogoPath() { return "thredds.jpg"; }
protected String getContextLogoAlt() { return "thredds"; }
protected String getInstituteLogoPath() { return "unidataLogo.gif"; }
protected String getInstituteLogoAlt() { return "unidata"; }
protected String getFolderIconPath() { return "folder.gif"; }
protected String getFolderIconAlt() { return "folder"; }
protected DataRootHandler catHandler; // singleton
// cache scouring
private Timer timer;
private org.slf4j.Logger cacheLog = org.slf4j.LoggerFactory.getLogger("cacheLogger");
private DiskCache2 aggCache;
public void init() throws ServletException {
super.init();
super.initContent(); // first time, create content directory
// get the URL context : URLS must be context/catalog/...
// cannot be overridded in ThreddsConfig
String contextPath = ServletUtil.getContextPath( this);
InvDatasetScan.setContext( contextPath);
InvDatasetScan.setCatalogServletName( "/catalog" );
// read in persistent user-defined params from threddsConfog.xml
ThreddsConfig.init(this.getServletContext(), contentPath+"/threddsConfig.xml", log);
// maybe change the logging
// ( String datePattern, long maxFileSize, int maxFiles )
if (ThreddsConfig.hasElement("Logging")) {
String datePattern = ThreddsConfig.get("Logging.DatePattern", null);
long maxFileSize = ThreddsConfig.getBytes("Logging.MaxFileSize", -1);
int maxFiles = ThreddsConfig.getInt("Logging.MaxFiles", 5);
changeLogs( datePattern, maxFileSize, maxFiles );
}
// NetcdfFileCache : default is allow 200 - 400 open files, cleanup every 10 minutes
int min = ThreddsConfig.getInt("NetcdfFileCache.minFiles", 200);
int max = ThreddsConfig.getInt("NetcdfFileCache.maxFiles", 400);
int secs = ThreddsConfig.getSeconds("NetcdfFileCache.scour", 10*60);
NetcdfFileCache.init(min, max, secs);
// NetcdfDatasetCache: // allow 100 - 200 open datasets, cleanup every 10 minutes
min = ThreddsConfig.getInt("NetcdfDatasetCache.minFiles", 100);
max = ThreddsConfig.getInt("NetcdfDatasetCache.maxFiles", 200);
secs = ThreddsConfig.getSeconds("NetcdfDatasetCache.scour", 10*60);
NetcdfDatasetCache.init(min, max, secs);
// HTTP file access : // allow 20 - 40 open datasets, cleanup every 10 minutes
min = ThreddsConfig.getInt("HTTPFileCache.minFiles", 25);
max = ThreddsConfig.getInt("HTTPFileCache.maxFiles", 40);
secs = ThreddsConfig.getSeconds("HTTPFileCache.scour", 10*60);
FileCache.init(min, max, secs);
// turn off Grib extend indexing; indexes are automatically done every 10 minutes externally
boolean extendIndex = ThreddsConfig.getBoolean("GribIndexing.setExtendIndex", false);
ucar.nc2.iosp.grib.GribServiceProvider.setExtendIndex( extendIndex);
boolean alwaysUseCache = ThreddsConfig.getBoolean("GribIndexing.alwaysUseCache", false);
ucar.nc2.iosp.grib.GribServiceProvider.setIndexAlwaysInCache( alwaysUseCache);
// optimization: netcdf-3 files can only grow, not have metadata changes
ucar.nc2.NetcdfFile.setProperty( "syncExtendOnly", "true");
// persist joinNew aggregations. default every 24 hours, delete stuff older than 30 days
String dir = ThreddsConfig.get("AggregationCache.dir", contentPath + "cacheAged/");
int scourSecs = ThreddsConfig.getSeconds("AggregationCache.scour", 24 * 60 * 60);
int maxAgeSecs = ThreddsConfig.getSeconds("AggregationCache.maxAge", 30 * 24 * 60 * 60);
aggCache = new DiskCache2(dir, false, maxAgeSecs/60, scourSecs/60);
Aggregation.setPersistenceCache( aggCache);
// how to choose the typical dataset ?
String typicalDataset = ThreddsConfig.get("Aggregation.typicalDataset", null);
if (null != typicalDataset)
Aggregation.setTypicalDatasetMode( typicalDataset);
// some paths cant be set otherwise
AggregationFmrc.setDefinitionDirectory( rootPath+"idd/modelInventory/" );
// handles all catalogs, including ones with DatasetScan elements, ie dynamic
DataRootHandler.init(contentPath, contextPath);
catHandler = DataRootHandler.getInstance();
catHandler.registerConfigListener( new RestrictedAccessConfigListener() );
initCatalogs();
catHandler.makeDebugActions();
DatasetHandler.makeDebugActions();
// Make sure the version info gets calculated.
getVersion();
// Nj22 disk cache
dir = ThreddsConfig.get("DiskCache.dir", contentPath + "cache/");
boolean alwaysUse = ThreddsConfig.getBoolean("DiskCache.alwaysUse", false);
scourSecs = ThreddsConfig.getSeconds("DiskCache.scour", 60 * 60);
long maxSize = ThreddsConfig.getBytes("DiskCache.maxSize", (long) 1000 * 1000 * 1000);
DiskCache.setRootDirectory(dir);
DiskCache.setCachePolicy(alwaysUse);
Calendar c = Calendar.getInstance(); // contains current startup time
c.add( Calendar.SECOND, scourSecs/2); // starting in half the scour time
timer = new Timer();
timer.scheduleAtFixedRate( new CacheScourTask(maxSize), c.getTime(), (long) 1000 * scourSecs );
HtmlWriter.init( contextPath, this.getContextName(), this.getVersion(), this.getDocsPath(),
this.getUserCssPath(),
this.getContextLogoPath(), this.getContextLogoAlt(),
this.getInstituteLogoPath(), this.getInstituteLogoAlt(),
this.getFolderIconPath(), this.getFolderIconAlt());
cacheLog.info("Restarted");
// Checking for double init seeing in intellij debug
log.info( "init(): done initializing <context= " + contextPath + ">." );
}
public void destroy() {
timer.cancel();
NetcdfFileCache.exit();
NetcdfDatasetCache.exit();
FileCache.exit();
aggCache.exit();
}
void initCatalogs() {
ArrayList catList = new ArrayList();
catList.add("catalog.xml"); // always first
getExtraCatalogs(catList);
catHandler.initCatalogs( catList);
}
private void getExtraCatalogs(List extraList) {
// if there are some roots in ThreddsConfig, then dont read extraCatalogs.txt
ThreddsConfig.getCatalogRoots(extraList);
if (extraList.size() > 0)
return;
// see if extraCatalogs.txt exists
File file = new File(contentPath + "extraCatalogs.txt");
if (file.exists()) {
try {
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
while (true) {
String line = reader.readLine();
if (line == null) break;
line = line.trim();
if (line.length() == 0) continue;
if ( line.startsWith( "#") ) continue; // Skip comment lines.
extraList.add( line);
}
fin.close();
} catch (IOException e) {
log.error("Error on getExtraCatalogs ",e);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletUtil.logServerAccessSetup( req );
try {
String path = ServletUtil.getRequestPath( req);
if (Debug.isSet("showRequest"))
System.out.println("**ThreddsDefault GET req="+ServletUtil.getRequest(req)+" path= "+path);
if (Debug.isSet("showRequestDetail"))
System.out.println( "**ThreddsDefault GET req="+ServletUtil.showRequestDetail(this, req));
if ( (path == null) || path.equals("/") ) {
String newPath = ServletUtil.getContextPath(this) +"/catalog.html";
res.sendRedirect( newPath);
return;
}
// these are the dataRoots, we allow raw access from the debug menu. must have tdsConfig rights
if (path.startsWith("/dataDir/")) {
path = path.substring(9);
File file = getMappedFile(path);
if ((file != null) && file.exists() && file.isDirectory())
HtmlWriter.getInstance().writeDirectory( res, file, path);
else
res.sendError(HttpServletResponse.SC_NOT_FOUND);
ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 );
return;
}
if (!path.startsWith("/content/")) {
// see if its a catalog
if (catHandler.processReqForCatalog( req, res)) {
return;
}
if (path.endsWith("/") && (getStaticFile(req) == null)) {
ServletUtil.forwardToCatalogServices( req, res);
return;
}
}
// if ( path.endsWith( "/latest.xml") ) {
// catHandler.processReqForLatestDataset( this, req, res);
// return;
// }
// debugging
if (path.equals("/debug") || path.equals("/debug/")) {
DebugHandler.doDebug(this, req, res);
return;
}
// debugging
if (path.equals("/catalogWait.xml")) {
log.debug("sleep 10 secs");
Thread.sleep(10000); // current thread sleeps
path = "/catalog.xml";
}
// debugging
if (path.equals("/testSessions") || path.equals("/testSecurity")) {
System.out.println( ServletUtil.showRequestDetail(this, req));
ServletUtil.showSession(req, System.out);
return;
}
// see if its a static file
File staticFile = getStaticFile(req);
if (staticFile == null) {
ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 );
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
/* if (path.startsWith("/fileServer")) {
ServletUtil.returnFile(this, req, res, staticFile, null);
return;
} */
// directory
if (staticFile.isDirectory()) {
// gotta end with a "/" for sanity reasons
if ( !path.endsWith("/")) {
String newPath = req.getRequestURI() +"/";
res.sendRedirect( newPath);
return;
}
// use an index.html file if it exists
File indexFile = new File( staticFile, "index.html");
if (indexFile.exists()) { // use it if it exists
staticFile = indexFile;
} else {
// normal thing to do
HtmlWriter.getInstance().writeDirectory(res, staticFile, path);
return;
}
}
ServletUtil.returnFile(this, req, res, staticFile, null);
} catch (Throwable t) {
t.printStackTrace();
log.error("doGet req= "+ServletUtil.getRequest(req)+" got Exception", t);
ServletUtil.handleException( t, res);
}
}
/* private void doCatalogHtml(HttpServletRequest req, HttpServletResponse res, String path )
throws IOException, ServletException {
// dispatch to CatalogHtml servlet
RequestDispatcher dispatch = req.getRequestDispatcher("/catalog.html?catalog="+path);
if (dispatch != null)
dispatch.forward(req, res);
else
res.sendError(HttpServletResponse.SC_NOT_FOUND);
} */
// Servlets that support HTTP GET requests and can quickly determine their last modification time should
// override this method. This makes browser and proxy caches work more effectively, reducing the load on
// server and network resources.
protected long getLastModified(HttpServletRequest req) {
File staticFile = getStaticFile( req);
if (staticFile == null)
return -1;
return staticFile.lastModified();
}
/** look for paths of the form
* /root/*
* /content/*
*
* then look to see if the file exists at:
* contentPath + path
* rootPath + path
*
* @param req
* @return File is found, else null
*/
private File getStaticFile(HttpServletRequest req) {
String path = req.getPathInfo();
if (path == null) return null;
/* if (path.startsWith("/fileServer/")) {
return getMappedFile(req.getPathInfo());
} */
boolean explicit = false;
String filename;
// special mapping to see top directories
if (path.startsWith("/root/")) {
explicit = true;
path = path.substring(5);
filename = ServletUtil.formFilename( rootPath, path);
} else if (path.startsWith("/content/")) {
explicit = true;
path = path.substring(8);
filename = ServletUtil.formFilename( contentPath, path);
} else {
// general case, doesnt start with /root/ or /content/
// we are getting content from the war file (webapps/thredds/) or from content/thredds/public
// first see if it exists under content
filename = ServletUtil.formFilename( contentPath+"public/", path);
if (filename != null) {
File file = new File( filename);
if (file.exists())
return file;
}
// otherwise try rootPath
filename = ServletUtil.formFilename( rootPath, path);
}
if (filename == null)
return null;
// these are ok if its an explicit root or content, since those are password protected
if (!explicit) {
if (path.endsWith("catalog.html") || path.endsWith("catalog.xml"))
return null;
String upper = filename.toUpperCase();
if (upper.indexOf("WEB-INF") != -1 || upper.indexOf("META-INF") != -1)
return null;
}
File file = new File( filename);
if (file.exists())
return file;
return null;
}
private File getMappedFile(String path) {
if (path == null) return null;
File file = catHandler.getCrawlableDatasetAsFile( path);
if ((file != null) && file.exists())
return file;
return null;
}
/***************************************************************************
* PUT requests: save a file in the content directory. Path must start with content.
*
* Request must be of the form
* config?server=serverName
*
* @param req The client's <code> HttpServletRequest</code> request object.
* @param res The server's <code> HttpServletResponse</code> response object.
*/
public void doPut(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletUtil.logServerAccessSetup( req );
String path = ServletUtil.getRequestPath( req);
if (Debug.isSet("showRequest"))
log.debug("ThreddsDefault PUT path= "+path);
if (path.startsWith("/content"))
path = path.substring(8);
else {
ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, 0 );
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
if (path != null) {
if (ServletUtil.saveFile( this, contentPath, path, req, res)) {
ServletUtil.logServerAccess( HttpServletResponse.SC_OK, 0 );
return; // LOOK - could trigger reread of config file
}
}
ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 );
res.sendError(HttpServletResponse.SC_NOT_FOUND);
}
// lame
static String getVersionStatic() { return version; }
protected String getVersion() {
if (version == null) {
String readme;
try {
readme = thredds.util.IO.readFile(rootPath+"docs/README.txt");
} catch (IOException e) {
return "unknown version";
}
int pos = readme.indexOf('\n');
if (pos > 0)
version = readme.substring(0, pos);
else
version = readme;
}
return version;
}
//////////////////////////////////////////////////////////////
// debugging
protected void makeCacheActions() {
DebugHandler debugHandler = DebugHandler.get("Caches");
DebugHandler.Action act;
act = new DebugHandler.Action("showCaches", "Show All Caches") {
public void doAction(DebugHandler.Event e) {
e.pw.println("NetcdfFileCache contents\n");
java.util.List cacheList = NetcdfFileCache.getCache();
for (int i = 0; i < cacheList.size(); i++) {
Object o = cacheList.get(i);
e.pw.println(" " + o);
}
e.pw.println("\nNetcdfDatasetCache contents");
cacheList = NetcdfDatasetCache.getCache();
for (int i = 0; i < cacheList.size(); i++) {
Object o = cacheList.get(i);
e.pw.println(" " + o);
}
e.pw.println("\nRAF Cache contents");
cacheList = ucar.unidata.io.FileCache.getCache();
for (int i = 0; i < cacheList.size(); i++) {
Object o = cacheList.get(i);
e.pw.println(" " + o);
}
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("clearCache", "Clear Caches") {
public void doAction(DebugHandler.Event e) {
NetcdfFileCache.clearCache(false);
NetcdfDatasetCache.clearCache(false);
ucar.unidata.io.FileCache.clearCache(false);
e.pw.println(" ClearCache ok");
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("forceNCCache", "Force clear NetcdfFileCache Cache") {
public void doAction(DebugHandler.Event e) {
NetcdfFileCache.clearCache(true);
e.pw.println(" NetcdfFileCache force clearCache done");
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("forceDSCache", "Force clear NetcdfDatasetCache Cache") {
public void doAction(DebugHandler.Event e) {
NetcdfDatasetCache.clearCache(true);
e.pw.println(" NetcdfDatasetCache force clearCache done");
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("forceRAFCache", "Force clear RAF FileCache Cache") {
public void doAction(DebugHandler.Event e) {
ucar.unidata.io.FileCache.clearCache(true);
e.pw.println(" RAF FileCache force clearCache done ");
}
};
debugHandler.addAction( act);
}
protected void makeDebugActions() {
DebugHandler debugHandler = DebugHandler.get("General");
DebugHandler.Action act;
act = new DebugHandler.Action("showVersion", "Show Build Version") {
public void doAction(DebugHandler.Event e) {
try {
thredds.util.IO.copyFile(rootPath+"docs/README.txt", e.pw);
} catch (Exception ioe) {
e.pw.println(ioe.getMessage());
}
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRuntime", "Show Runtime info") {
public void doAction(DebugHandler.Event e) {
Runtime runt = Runtime.getRuntime();
double scale = 1.0/(1000.0 * 1000.0);
e.pw.println(" freeMemory= "+ scale * runt.freeMemory()+" Mb");
e.pw.println(" totalMemory= "+scale * runt.totalMemory()+" Mb");
e.pw.println(" maxMemory= "+scale * runt.maxMemory()+" Mb");
e.pw.println(" availableProcessors= "+runt.availableProcessors());
e.pw.println();
ServletUtil.showThreads(e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showFlags", "Show Debugging Flags") {
public void doAction(DebugHandler.Event e) {
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("toggleFlag", null) {
public void doAction(DebugHandler.Event e) {
if (e.target != null) {
String flag = e.target;
Debug.set( flag, !Debug.isSet(flag));
} else
e.pw.println(" Must be toggleFlag=<flagName>");
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showLoggers", "Show Log4J info") {
public void doAction(DebugHandler.Event e) {
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("setLogger", null) {
public void doAction(DebugHandler.Event e) {
if (e.target == null) {
e.pw.println(" Must be setLogger=loggerName");
return;
}
StringTokenizer stoker = new StringTokenizer( e.target,"&=");
if (stoker.countTokens() < 3) {
e.pw.println(" Must be setLogger=loggerName&setLevel=levelName");
return;
}
String loggerName = stoker.nextToken();
stoker.nextToken(); // level=
String levelName = stoker.nextToken();
boolean isRootLogger = loggerName.equals("root");
if (!isRootLogger && LogManager.exists(loggerName) == null) {
e.pw.println(" Unknown logger="+loggerName);
return;
}
if (Level.toLevel(levelName, null) == null) {
e.pw.println(" Unknown level="+levelName);
return;
}
Logger log = isRootLogger ? LogManager.getRootLogger() : LogManager.getLogger(loggerName);
log.setLevel( Level.toLevel(levelName));
e.pw.println(loggerName+" set to "+levelName);
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRequest", "Show HTTP Request info") {
public void doAction(DebugHandler.Event e) {
e.pw.println(ServletUtil.showRequestDetail( ThreddsDefaultServlet.this, e.req));
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("showServerInfo", "Show Server info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServerInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showServletInfo", "Show Servlet info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServletInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSession", "Show HTTP Session info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showSession( e.req, e.res, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSecurity", "Show Security info") {
public void doAction(DebugHandler.Event e) {
e.pw.println( ServletUtil.showSecurity( e.req, "admin"));
}
};
debugHandler.addAction(act);
makeCacheActions();
debugHandler = DebugHandler.get("catalogs");
act = new DebugHandler.Action("reinit", "Reinitialize") {
public void doAction(DebugHandler.Event e) {
// TODO The calls to reinit() and initCatalogs() are synchronized but should be atomic.
- // TODO Should change this to build config data structure and synch only when replacing the old with the new structure. catHandler.reinit();
+ // TODO Should change this to build config data structure and synch only when replacing the old with the new structure.
+ catHandler.reinit();
ThreddsConfig.readConfig(log);
initCatalogs();
e.pw.println( "reinit ok");
}
};
debugHandler.addAction( act);
}
void showFlags(HttpServletRequest req, PrintStream pw) {
Iterator iter = Debug.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
String url = req.getRequestURI() + "?toggleFlag=" + key;
pw.println(" <a href='" +url+"'>"+key+" = "+Debug.isSet(key)+"</a>");
}
}
private void changeLogs( String datePattern, long maxFileSize, int maxFiles ) {
// get the existing appender
Logger logger = LogManager.getLogger("thredds");
FileAppender fapp = (FileAppender) logger.getAppender("threddsServlet");
PatternLayout playout = (PatternLayout) fapp.getLayout();
String filename = fapp.getFile();
// create a new one
Appender newAppender = null;
try {
if (null != datePattern) {
newAppender = new DailyRollingFileAppender(playout, filename, datePattern);
} else if (maxFileSize > 0) {
RollingFileAppender rapp = new RollingFileAppender(playout, filename);
rapp.setMaximumFileSize(maxFileSize);
rapp.setMaxBackupIndex(maxFiles);
newAppender = rapp;
} else {
return;
}
} catch (IOException ioe) {
log.error("Error changing the logger", ioe);
}
// replace wherever you find it
Logger root = LogManager.getRootLogger();
replaceAppender( root, "threddsServlet", newAppender);
Enumeration logEnums = LogManager.getCurrentLoggers();
while (logEnums.hasMoreElements()) {
Logger log = (Logger) logEnums.nextElement();
replaceAppender( log, "threddsServlet", newAppender);
}
}
private void replaceAppender(Logger logger, String want, Appender replaceWith) {
Enumeration appenders = logger.getAllAppenders();
while (appenders.hasMoreElements()) {
Appender app = (Appender) appenders.nextElement();
if (app.getName().equals(want)) {
logger.removeAppender(app);
logger.addAppender(replaceWith);
}
}
}
void showLoggers(HttpServletRequest req, PrintStream pw) {
Logger root = LogManager.getRootLogger();
showLogger( req, root, pw);
Enumeration logEnums = LogManager.getCurrentLoggers();
List loggersSorted = Collections.list( logEnums);
Collections.sort( loggersSorted, new LoggerComparator());
Iterator loggers = loggersSorted.iterator();
while (loggers.hasNext()) {
Logger logger = (Logger) loggers.next();
showLogger( req, logger, pw);
}
}
private void showLogger(HttpServletRequest req, Logger logger, PrintStream pw) {
pw.print(" logger = "+logger.getName()+" level= ");
String url = req.getRequestURI() + "?setLogger=" + logger.getName()+"&level=";
showLevel( url, Level.ALL, logger.getEffectiveLevel(), pw);
showLevel( url, Level.DEBUG, logger.getEffectiveLevel(), pw);
showLevel( url, Level.INFO, logger.getEffectiveLevel(), pw);
showLevel( url, Level.WARN, logger.getEffectiveLevel(), pw);
showLevel( url, Level.ERROR, logger.getEffectiveLevel(), pw);
showLevel( url, Level.FATAL, logger.getEffectiveLevel(), pw);
showLevel( url, Level.OFF, logger.getEffectiveLevel(), pw);
pw.println();
Enumeration appenders = logger.getAllAppenders();
while (appenders.hasMoreElements()) {
Appender app = (Appender) appenders.nextElement();
pw.println(" appender= "+app.getName()+" "+app.getClass().getName());
Layout layout = app.getLayout();
if (layout instanceof PatternLayout) {
PatternLayout playout = (PatternLayout) layout;
pw.println(" layout pattern= "+playout.getConversionPattern());
}
if (app instanceof AppenderSkeleton) {
AppenderSkeleton skapp = (AppenderSkeleton) app;
if (skapp.getThreshold() != null)
pw.println(" threshold="+skapp.getThreshold());
}
if (app instanceof FileAppender) {
FileAppender fapp = (FileAppender) app;
pw.println(" file="+fapp.getFile());
}
}
}
private void showLevel(String baseUrl, Level show, Level current, PrintStream pw) {
if (show.toInt() != current.toInt())
pw.print(" <a href='"+baseUrl+show+"'>"+show+"</a>");
else
pw.print(" "+show);
}
private class LoggerComparator implements Comparator {
public int compare(Object o1, Object o2) {
Logger l1 = (Logger) o1;
Logger l2 = (Logger) o2;
return l1.getName().compareTo( l2.getName());
}
public boolean equals( Object o) {
return this == o;
}
}
private class CacheScourTask extends TimerTask {
long maxBytes;
CacheScourTask(long maxBytes ) {
this.maxBytes = maxBytes;
}
public void run() {
StringBuffer sbuff = new StringBuffer();
DiskCache.cleanCache(maxBytes, sbuff); // 1 Gbyte
sbuff.append("----------------------\n");
cacheLog.info(sbuff.toString());
}
}
private class RestrictedAccessConfigListener implements DataRootHandler.ConfigListener
{
volatile boolean initializing;
public RestrictedAccessConfigListener()
{
initializing = false;
}
public void configStart()
{
this.initializing = true;
}
public void configEnd()
{
this.initializing = false;
}
public void configCatalog( InvCatalog catalog )
{
return;
}
public void configDataset( InvDataset dataset )
{
// check for resource control
if ( dataset.getRestrictAccess() != null )
DatasetHandler.putResourceControl( (InvDatasetImpl) dataset );
}
}
}
| true | true | protected void makeDebugActions() {
DebugHandler debugHandler = DebugHandler.get("General");
DebugHandler.Action act;
act = new DebugHandler.Action("showVersion", "Show Build Version") {
public void doAction(DebugHandler.Event e) {
try {
thredds.util.IO.copyFile(rootPath+"docs/README.txt", e.pw);
} catch (Exception ioe) {
e.pw.println(ioe.getMessage());
}
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRuntime", "Show Runtime info") {
public void doAction(DebugHandler.Event e) {
Runtime runt = Runtime.getRuntime();
double scale = 1.0/(1000.0 * 1000.0);
e.pw.println(" freeMemory= "+ scale * runt.freeMemory()+" Mb");
e.pw.println(" totalMemory= "+scale * runt.totalMemory()+" Mb");
e.pw.println(" maxMemory= "+scale * runt.maxMemory()+" Mb");
e.pw.println(" availableProcessors= "+runt.availableProcessors());
e.pw.println();
ServletUtil.showThreads(e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showFlags", "Show Debugging Flags") {
public void doAction(DebugHandler.Event e) {
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("toggleFlag", null) {
public void doAction(DebugHandler.Event e) {
if (e.target != null) {
String flag = e.target;
Debug.set( flag, !Debug.isSet(flag));
} else
e.pw.println(" Must be toggleFlag=<flagName>");
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showLoggers", "Show Log4J info") {
public void doAction(DebugHandler.Event e) {
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("setLogger", null) {
public void doAction(DebugHandler.Event e) {
if (e.target == null) {
e.pw.println(" Must be setLogger=loggerName");
return;
}
StringTokenizer stoker = new StringTokenizer( e.target,"&=");
if (stoker.countTokens() < 3) {
e.pw.println(" Must be setLogger=loggerName&setLevel=levelName");
return;
}
String loggerName = stoker.nextToken();
stoker.nextToken(); // level=
String levelName = stoker.nextToken();
boolean isRootLogger = loggerName.equals("root");
if (!isRootLogger && LogManager.exists(loggerName) == null) {
e.pw.println(" Unknown logger="+loggerName);
return;
}
if (Level.toLevel(levelName, null) == null) {
e.pw.println(" Unknown level="+levelName);
return;
}
Logger log = isRootLogger ? LogManager.getRootLogger() : LogManager.getLogger(loggerName);
log.setLevel( Level.toLevel(levelName));
e.pw.println(loggerName+" set to "+levelName);
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRequest", "Show HTTP Request info") {
public void doAction(DebugHandler.Event e) {
e.pw.println(ServletUtil.showRequestDetail( ThreddsDefaultServlet.this, e.req));
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("showServerInfo", "Show Server info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServerInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showServletInfo", "Show Servlet info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServletInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSession", "Show HTTP Session info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showSession( e.req, e.res, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSecurity", "Show Security info") {
public void doAction(DebugHandler.Event e) {
e.pw.println( ServletUtil.showSecurity( e.req, "admin"));
}
};
debugHandler.addAction(act);
makeCacheActions();
debugHandler = DebugHandler.get("catalogs");
act = new DebugHandler.Action("reinit", "Reinitialize") {
public void doAction(DebugHandler.Event e) {
// TODO The calls to reinit() and initCatalogs() are synchronized but should be atomic.
// TODO Should change this to build config data structure and synch only when replacing the old with the new structure. catHandler.reinit();
ThreddsConfig.readConfig(log);
initCatalogs();
e.pw.println( "reinit ok");
}
};
debugHandler.addAction( act);
}
| protected void makeDebugActions() {
DebugHandler debugHandler = DebugHandler.get("General");
DebugHandler.Action act;
act = new DebugHandler.Action("showVersion", "Show Build Version") {
public void doAction(DebugHandler.Event e) {
try {
thredds.util.IO.copyFile(rootPath+"docs/README.txt", e.pw);
} catch (Exception ioe) {
e.pw.println(ioe.getMessage());
}
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRuntime", "Show Runtime info") {
public void doAction(DebugHandler.Event e) {
Runtime runt = Runtime.getRuntime();
double scale = 1.0/(1000.0 * 1000.0);
e.pw.println(" freeMemory= "+ scale * runt.freeMemory()+" Mb");
e.pw.println(" totalMemory= "+scale * runt.totalMemory()+" Mb");
e.pw.println(" maxMemory= "+scale * runt.maxMemory()+" Mb");
e.pw.println(" availableProcessors= "+runt.availableProcessors());
e.pw.println();
ServletUtil.showThreads(e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showFlags", "Show Debugging Flags") {
public void doAction(DebugHandler.Event e) {
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("toggleFlag", null) {
public void doAction(DebugHandler.Event e) {
if (e.target != null) {
String flag = e.target;
Debug.set( flag, !Debug.isSet(flag));
} else
e.pw.println(" Must be toggleFlag=<flagName>");
showFlags( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showLoggers", "Show Log4J info") {
public void doAction(DebugHandler.Event e) {
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("setLogger", null) {
public void doAction(DebugHandler.Event e) {
if (e.target == null) {
e.pw.println(" Must be setLogger=loggerName");
return;
}
StringTokenizer stoker = new StringTokenizer( e.target,"&=");
if (stoker.countTokens() < 3) {
e.pw.println(" Must be setLogger=loggerName&setLevel=levelName");
return;
}
String loggerName = stoker.nextToken();
stoker.nextToken(); // level=
String levelName = stoker.nextToken();
boolean isRootLogger = loggerName.equals("root");
if (!isRootLogger && LogManager.exists(loggerName) == null) {
e.pw.println(" Unknown logger="+loggerName);
return;
}
if (Level.toLevel(levelName, null) == null) {
e.pw.println(" Unknown level="+levelName);
return;
}
Logger log = isRootLogger ? LogManager.getRootLogger() : LogManager.getLogger(loggerName);
log.setLevel( Level.toLevel(levelName));
e.pw.println(loggerName+" set to "+levelName);
showLoggers( e.req, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showRequest", "Show HTTP Request info") {
public void doAction(DebugHandler.Event e) {
e.pw.println(ServletUtil.showRequestDetail( ThreddsDefaultServlet.this, e.req));
}
};
debugHandler.addAction( act);
act = new DebugHandler.Action("showServerInfo", "Show Server info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServerInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showServletInfo", "Show Servlet info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showServletInfo( ThreddsDefaultServlet.this, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSession", "Show HTTP Session info") {
public void doAction(DebugHandler.Event e) {
ServletUtil.showSession( e.req, e.res, e.pw);
}
};
debugHandler.addAction(act);
act = new DebugHandler.Action("showSecurity", "Show Security info") {
public void doAction(DebugHandler.Event e) {
e.pw.println( ServletUtil.showSecurity( e.req, "admin"));
}
};
debugHandler.addAction(act);
makeCacheActions();
debugHandler = DebugHandler.get("catalogs");
act = new DebugHandler.Action("reinit", "Reinitialize") {
public void doAction(DebugHandler.Event e) {
// TODO The calls to reinit() and initCatalogs() are synchronized but should be atomic.
// TODO Should change this to build config data structure and synch only when replacing the old with the new structure.
catHandler.reinit();
ThreddsConfig.readConfig(log);
initCatalogs();
e.pw.println( "reinit ok");
}
};
debugHandler.addAction( act);
}
|
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichBean.java
index 5700b015..2742340b 100644
--- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichBean.java
+++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichBean.java
@@ -1,316 +1,317 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 org.richfaces.tests.metamer.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Managed bean storing glogal setting for the application, e.g. skin.
*
* @author <a href="mailto:[email protected]">Pavol Pitonak</a>
* @version $Revision$
*/
@ManagedBean
@SessionScoped
public class RichBean implements Serializable {
private static final long serialVersionUID = 5590865106686406193L;
private Logger logger;
private String skin;
private List<SelectItem> skinningList;
private Skinning skinning;
private List<String> skins;
private boolean reDefault;
private boolean reComponent;
private boolean reTests;
private boolean log;
private String component;
private Map<String, String> components; // [a4jCommandLink; A4J Command Link]
private String container;
public enum Skinning {
NONE, SKINNING, SKINNING_CLASSES
}
@PostConstruct
public void init() {
logger = LoggerFactory.getLogger(RichBean.class);
createSkinList();
createComponentsMap();
component = "none";
container = "plain";
skin = "blueSky";
skinningList = new ArrayList<SelectItem>();
skinningList.add(new SelectItem(Skinning.NONE));
skinningList.add(new SelectItem(Skinning.SKINNING));
skinningList.add(new SelectItem(Skinning.SKINNING_CLASSES));
skinning = Skinning.SKINNING;
reTests = false;
reComponent = true;
}
private void createComponentsMap() {
components = new TreeMap<String, String>();
components.put("a4jActionListener", "A4J Action Listener");
components.put("a4jAjax", "A4J Ajax");
components.put("a4jAttachQueue", "A4J Attach Queue");
components.put("a4jCommandLink", "A4J Command Link");
components.put("a4jCommandButton", "A4J Command Button");
components.put("a4jJSFunction", "A4J JavaScript Function");
components.put("a4jLog", "A4J Log");
components.put("a4jMediaOutput", "A4J Media Output");
components.put("a4jOutputPanel", "A4J Output Panel");
components.put("a4jParam", "A4J Action Parameter");
components.put("a4jPoll", "A4J Poll");
components.put("a4jPush", "A4J Push");
components.put("a4jQueue", "A4J Queue");
components.put("a4jRegion", "A4J Region");
components.put("a4jRepeat", "A4J Repeat");
components.put("commandButton", "JSF Command Button");
+ components.put("hDataTable", "JSF Data Table");
components.put("richComponentControl", "Rich Component Control");
components.put("richDataGrid", "Rich Data Grid");
components.put("richDataScroller", "Rich Data Scroller");
components.put("richDataTable", "Rich Data Table");
components.put("richExtendedDataTable", "Rich Extended Data Table");
components.put("richFunctions", "Rich Functions");
components.put("richJQuery", "Rich jQuery");
components.put("richList", "Rich List");
components.put("richPanel", "Rich Panel");
components.put("richSubTable", "Rich Subtable");
components.put("richSubTableToggleControl", "Rich Subtable Toggle Control");
components.put("richToggleControl", "Rich Toggle Control");
components.put("richTogglePanel", "Rich Toggle Panel");
}
private void createSkinList() {
skins = new ArrayList<String>();
skins.add("blueSky");
skins.add("classic");
skins.add("deepMarine");
skins.add("emeraldTown");
skins.add("japanCherry");
skins.add("ruby");
skins.add("wine");
}
/**
* Getter for user's skin.
*
* @return a RichFaces skin
*/
public String getSkin() {
return skin;
}
/**
* Setter for user's skin.
*
* @param skin
* a RichFaces skin
*/
public void setSkin(String skin) {
this.skin = skin;
}
public String getSkinning() {
if (skinning == Skinning.SKINNING) {
return "enabled";
} else {
return "disabled";
}
}
public void setSkinning(String skinning) {
this.skinning = Skinning.valueOf(skinning);
}
public String getSkinningClasses() {
if (skinning == Skinning.SKINNING_CLASSES) {
return "enabled";
} else {
return "disabled";
}
}
public void setSkinningClasses(String skinningClasses) {
this.skinning = Skinning.valueOf(skinningClasses);
}
public List<SelectItem> getSkinningList() {
return skinningList;
}
public void setSkins(List<String> skins) {
this.skins = skins;
}
public List<String> getSkins() {
return skins;
}
public void setReDefault(boolean reDefault) {
this.reDefault = reDefault;
}
public boolean isReDefault() {
return reDefault;
}
public void setReComponent(boolean reComponent) {
this.reComponent = reComponent;
}
public boolean isReComponent() {
return reComponent;
}
public void setLog(boolean log) {
this.log = log;
}
public boolean isLog() {
return log;
}
public void setComponent(String component) {
this.component = component;
}
public String getComponent() {
return component;
}
public Set<String> getComponentList() {
return components.keySet();
}
/**
* @return the components
*/
public Map<String, String> getComponents() {
return components;
}
/**
* @param components the components to set
*/
public void setComponents(Map<String, String> components) {
this.components = components;
}
public List<String> getRichComponents() {
List<String> richComponents = new ArrayList<String>();
for (String aComponent : components.keySet()) {
if (aComponent.startsWith("rich")) {
richComponents.add(aComponent);
}
}
return richComponents;
}
public List<String> getA4JComponents() {
List<String> a4jComponents = new ArrayList<String>();
for (String aComponent : components.keySet()) {
if (aComponent.startsWith("a4j")) {
a4jComponents.add(aComponent);
}
}
return a4jComponents;
}
public List<String> getOtherComponents() {
List<String> otherComponents = new ArrayList<String>();
for (String aComponent : components.keySet()) {
if (!aComponent.startsWith("rich") && !aComponent.startsWith("a4j")) {
otherComponents.add(aComponent);
}
}
return otherComponents;
}
public String getContainer() {
return container;
}
public void setContainer(String container) {
this.container = container;
}
public boolean isReTests() {
return reTests;
}
public void setReTests(boolean reTests) {
this.reTests = reTests;
}
public String getTestsPage() {
if (component.equals("none")) {
return "/blank.xhtml";
} else {
return String.format("/components/%s/tests.xhtml", component);
}
}
public String invalidateSession() {
Object session = FacesContext.getCurrentInstance().getExternalContext().getSession(true);
if (session == null) {
return "/index";
}
if (session instanceof HttpSession) {
((HttpSession) session).invalidate();
return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=tru";
}
throw new IllegalStateException();
}
public static void logToPage(String msg) {
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory factory = ctx.getApplication().getExpressionFactory();
ValueExpression exp = factory.createValueExpression(ctx.getELContext(), "#{phasesBean.phases}", List.class);
List<String> phases = (List<String>) exp.getValue(ctx.getELContext());
phases.add(msg);
}
}
| true | true | private void createComponentsMap() {
components = new TreeMap<String, String>();
components.put("a4jActionListener", "A4J Action Listener");
components.put("a4jAjax", "A4J Ajax");
components.put("a4jAttachQueue", "A4J Attach Queue");
components.put("a4jCommandLink", "A4J Command Link");
components.put("a4jCommandButton", "A4J Command Button");
components.put("a4jJSFunction", "A4J JavaScript Function");
components.put("a4jLog", "A4J Log");
components.put("a4jMediaOutput", "A4J Media Output");
components.put("a4jOutputPanel", "A4J Output Panel");
components.put("a4jParam", "A4J Action Parameter");
components.put("a4jPoll", "A4J Poll");
components.put("a4jPush", "A4J Push");
components.put("a4jQueue", "A4J Queue");
components.put("a4jRegion", "A4J Region");
components.put("a4jRepeat", "A4J Repeat");
components.put("commandButton", "JSF Command Button");
components.put("richComponentControl", "Rich Component Control");
components.put("richDataGrid", "Rich Data Grid");
components.put("richDataScroller", "Rich Data Scroller");
components.put("richDataTable", "Rich Data Table");
components.put("richExtendedDataTable", "Rich Extended Data Table");
components.put("richFunctions", "Rich Functions");
components.put("richJQuery", "Rich jQuery");
components.put("richList", "Rich List");
components.put("richPanel", "Rich Panel");
components.put("richSubTable", "Rich Subtable");
components.put("richSubTableToggleControl", "Rich Subtable Toggle Control");
components.put("richToggleControl", "Rich Toggle Control");
components.put("richTogglePanel", "Rich Toggle Panel");
}
| private void createComponentsMap() {
components = new TreeMap<String, String>();
components.put("a4jActionListener", "A4J Action Listener");
components.put("a4jAjax", "A4J Ajax");
components.put("a4jAttachQueue", "A4J Attach Queue");
components.put("a4jCommandLink", "A4J Command Link");
components.put("a4jCommandButton", "A4J Command Button");
components.put("a4jJSFunction", "A4J JavaScript Function");
components.put("a4jLog", "A4J Log");
components.put("a4jMediaOutput", "A4J Media Output");
components.put("a4jOutputPanel", "A4J Output Panel");
components.put("a4jParam", "A4J Action Parameter");
components.put("a4jPoll", "A4J Poll");
components.put("a4jPush", "A4J Push");
components.put("a4jQueue", "A4J Queue");
components.put("a4jRegion", "A4J Region");
components.put("a4jRepeat", "A4J Repeat");
components.put("commandButton", "JSF Command Button");
components.put("hDataTable", "JSF Data Table");
components.put("richComponentControl", "Rich Component Control");
components.put("richDataGrid", "Rich Data Grid");
components.put("richDataScroller", "Rich Data Scroller");
components.put("richDataTable", "Rich Data Table");
components.put("richExtendedDataTable", "Rich Extended Data Table");
components.put("richFunctions", "Rich Functions");
components.put("richJQuery", "Rich jQuery");
components.put("richList", "Rich List");
components.put("richPanel", "Rich Panel");
components.put("richSubTable", "Rich Subtable");
components.put("richSubTableToggleControl", "Rich Subtable Toggle Control");
components.put("richToggleControl", "Rich Toggle Control");
components.put("richTogglePanel", "Rich Toggle Panel");
}
|
diff --git a/utils/CompareTrees.java b/utils/CompareTrees.java
index 699359df9..fca1de827 100644
--- a/utils/CompareTrees.java
+++ b/utils/CompareTrees.java
@@ -1,103 +1,103 @@
// CompareTrees.java
import java.io.File;
import java.util.Arrays;
/**
* Compares the paths specified as command line arguments, outputting all
* differences between them (i.e., files and directories present in one path
* but not in the other). This implementation does note when two files do not
* have matching file sizes, but does not check byte-for-byte equality when
* the file sizes match.
*/
public class CompareTrees {
public static final void main(String[] args) {
if (args.length < 2) {
System.out.println("Please specify two paths to compare.");
System.exit(1);
}
String path1 = args[0];
String path2 = args[1];
File dir1 = new File(path1);
File dir2 = new File(path2);
if (!dir1.exists() || !dir1.isDirectory()) {
System.out.println(path1 + " is invalid.");
System.exit(2);
}
if (!dir2.exists() || !dir2.isDirectory()) {
System.out.println(path2 + " is invalid.");
System.exit(3);
}
compare(dir1, dir2);
}
public static final void compare(File dir1, File dir2) {
if (dir1 == null && dir2 == null) return;
if (dir2 == null) {
- System.out.println("<<< " + dir1 + " (" +
- dir1.listFiles().length + " files)");
+ System.out.println("<<< " + dir1 + "\t[" +
+ dir1.listFiles().length + " files]");
return;
}
if (dir1 == null) {
- System.out.println(">>> " + dir2 + " (" +
- dir2.listFiles().length + " files)");
+ System.out.println(">>> " + dir2 + "\t[" +
+ dir2.listFiles().length + " files]");
return;
}
File[] list1 = dir1.listFiles();
File[] list2 = dir2.listFiles();
if (list1 == null) list1 = new File[0];
if (list2 == null) list2 = new File[0];
Arrays.sort(list1);
Arrays.sort(list2);
int ndx1 = 0, ndx2 = 0;
while (ndx1 < list1.length && ndx2 < list2.length) {
boolean d1 = list1[ndx1].isDirectory();
boolean d2 = list2[ndx2].isDirectory();
int c = list1[ndx1].getName().compareToIgnoreCase(list2[ndx2].getName());
if (c < 0) {
System.out.print("<<< " + list1[ndx1++] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
else if (c > 0) {
- System.out.println(">>> " + list2[ndx2++] + "\tmissing");
+ System.out.print(">>> " + list2[ndx2++] + "\t[missing]");
if (d2) System.out.print(" [directory]");
System.out.println();
}
else {
if ((d1 && !d2)) System.out.println("!D! " + list2[ndx1]);
else if (!d1 && d2) System.out.println("!D! " + list1[ndx1]);
else if (d1 && d2) compare(list1[ndx1], list2[ndx2]);
else {
long len1 = list1[ndx1].length();
long len2 = list2[ndx2].length();
if (len1 != len2) {
System.out.println("!S! " + list1[ndx1] +
"\t[" + len1 + " vs " + len2 + "]");
}
}
ndx1++;
ndx2++;
}
}
if (ndx1 < list1.length) {
for (int i=ndx1; i<list1.length; i++) {
boolean d1 = list1[i].isDirectory();
System.out.print("<<< " + list1[i] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
}
if (ndx2 < list2.length) {
for (int i=ndx2; i<list2.length; i++) {
boolean d2 = list2[i].isDirectory();
- System.out.println(">>> " + list2[i] + "\tmissing");
+ System.out.print(">>> " + list2[i] + "\t[missing]");
if (d2) System.out.print(" [directory]");
System.out.println();
}
}
}
}
| false | true | public static final void compare(File dir1, File dir2) {
if (dir1 == null && dir2 == null) return;
if (dir2 == null) {
System.out.println("<<< " + dir1 + " (" +
dir1.listFiles().length + " files)");
return;
}
if (dir1 == null) {
System.out.println(">>> " + dir2 + " (" +
dir2.listFiles().length + " files)");
return;
}
File[] list1 = dir1.listFiles();
File[] list2 = dir2.listFiles();
if (list1 == null) list1 = new File[0];
if (list2 == null) list2 = new File[0];
Arrays.sort(list1);
Arrays.sort(list2);
int ndx1 = 0, ndx2 = 0;
while (ndx1 < list1.length && ndx2 < list2.length) {
boolean d1 = list1[ndx1].isDirectory();
boolean d2 = list2[ndx2].isDirectory();
int c = list1[ndx1].getName().compareToIgnoreCase(list2[ndx2].getName());
if (c < 0) {
System.out.print("<<< " + list1[ndx1++] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
else if (c > 0) {
System.out.println(">>> " + list2[ndx2++] + "\tmissing");
if (d2) System.out.print(" [directory]");
System.out.println();
}
else {
if ((d1 && !d2)) System.out.println("!D! " + list2[ndx1]);
else if (!d1 && d2) System.out.println("!D! " + list1[ndx1]);
else if (d1 && d2) compare(list1[ndx1], list2[ndx2]);
else {
long len1 = list1[ndx1].length();
long len2 = list2[ndx2].length();
if (len1 != len2) {
System.out.println("!S! " + list1[ndx1] +
"\t[" + len1 + " vs " + len2 + "]");
}
}
ndx1++;
ndx2++;
}
}
if (ndx1 < list1.length) {
for (int i=ndx1; i<list1.length; i++) {
boolean d1 = list1[i].isDirectory();
System.out.print("<<< " + list1[i] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
}
if (ndx2 < list2.length) {
for (int i=ndx2; i<list2.length; i++) {
boolean d2 = list2[i].isDirectory();
System.out.println(">>> " + list2[i] + "\tmissing");
if (d2) System.out.print(" [directory]");
System.out.println();
}
}
}
| public static final void compare(File dir1, File dir2) {
if (dir1 == null && dir2 == null) return;
if (dir2 == null) {
System.out.println("<<< " + dir1 + "\t[" +
dir1.listFiles().length + " files]");
return;
}
if (dir1 == null) {
System.out.println(">>> " + dir2 + "\t[" +
dir2.listFiles().length + " files]");
return;
}
File[] list1 = dir1.listFiles();
File[] list2 = dir2.listFiles();
if (list1 == null) list1 = new File[0];
if (list2 == null) list2 = new File[0];
Arrays.sort(list1);
Arrays.sort(list2);
int ndx1 = 0, ndx2 = 0;
while (ndx1 < list1.length && ndx2 < list2.length) {
boolean d1 = list1[ndx1].isDirectory();
boolean d2 = list2[ndx2].isDirectory();
int c = list1[ndx1].getName().compareToIgnoreCase(list2[ndx2].getName());
if (c < 0) {
System.out.print("<<< " + list1[ndx1++] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
else if (c > 0) {
System.out.print(">>> " + list2[ndx2++] + "\t[missing]");
if (d2) System.out.print(" [directory]");
System.out.println();
}
else {
if ((d1 && !d2)) System.out.println("!D! " + list2[ndx1]);
else if (!d1 && d2) System.out.println("!D! " + list1[ndx1]);
else if (d1 && d2) compare(list1[ndx1], list2[ndx2]);
else {
long len1 = list1[ndx1].length();
long len2 = list2[ndx2].length();
if (len1 != len2) {
System.out.println("!S! " + list1[ndx1] +
"\t[" + len1 + " vs " + len2 + "]");
}
}
ndx1++;
ndx2++;
}
}
if (ndx1 < list1.length) {
for (int i=ndx1; i<list1.length; i++) {
boolean d1 = list1[i].isDirectory();
System.out.print("<<< " + list1[i] + "\t[missing]");
if (d1) System.out.print(" [directory]");
System.out.println();
}
}
if (ndx2 < list2.length) {
for (int i=ndx2; i<list2.length; i++) {
boolean d2 = list2[i].isDirectory();
System.out.print(">>> " + list2[i] + "\t[missing]");
if (d2) System.out.print(" [directory]");
System.out.println();
}
}
}
|
diff --git a/src/main/java/hudson/plugins/cvs_tag/CvsTagPlugin.java b/src/main/java/hudson/plugins/cvs_tag/CvsTagPlugin.java
index e0abd85..58f84ee 100644
--- a/src/main/java/hudson/plugins/cvs_tag/CvsTagPlugin.java
+++ b/src/main/java/hudson/plugins/cvs_tag/CvsTagPlugin.java
@@ -1,189 +1,189 @@
package hudson.plugins.cvs_tag;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Map;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.scm.CVSSCM;
import hudson.util.ArgumentListBuilder;
import org.codehaus.groovy.control.CompilerConfiguration;
/**
* @author Brendt Lucas
*/
public class CvsTagPlugin
{
static final String DESCRIPTION = "Perform CVS tagging on succesful build";
static final String CONFIG_PREFIX = "cvstag.";
private CvsTagPlugin()
{
}
private static AbstractProject getRootProject(AbstractProject abstractProject)
{
if (abstractProject.getParent() instanceof Hudson)
{
return abstractProject;
}
else
{
return getRootProject((AbstractProject) abstractProject.getParent());
}
}
public static boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, String tagName)
{
PrintStream logger = listener.getLogger();
if (!Result.SUCCESS.equals(build.getResult()))
{
logger.println("Skipping CVS Tagging as build result was not successful.");
return true;
}
AbstractProject rootProject = getRootProject(build.getProject());
if (!(rootProject.getScm() instanceof CVSSCM))
{
logger.println("CVS Tag plugin does not support tagging for SCM " + rootProject.getScm() + ".");
return true;
}
CVSSCM scm = CVSSCM.class.cast(rootProject.getScm());
// Evaluate the groovy tag name
Map<String, String> env = build.getEnvVars();
tagName = evalGroovyExpression(env, tagName);
// Get the modules we will be tagging
String modules = arrayToString(scm.getAllModulesNormalized(), " ");
// -D option for rtag command.
// Tag the most recent revision no later than <date> ...
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(build.getTimestamp().getTime());
ArgumentListBuilder cmd = new ArgumentListBuilder();
if (scm.getBranch() != null)
{
- // cvs -d cvsRoot rtag -r branchName -D toDate tagName modules
- cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-r", scm.getBranch(), "-D", date, tagName, modules);
+ // cvs -d cvsRoot rtag -r branchName tagName modules
+ cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-r", scm.getBranch(), tagName, modules);
}
else
{
// cvs -d cvsRoot rtag -D toDate tagName modules
cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-D", date, tagName, modules);
}
logger.println("Executing tag command: " + cmd.toStringWithQuote());
File tempDir = null;
try
{
tempDir = Util.createTempDir();
int exitCode = launcher.launch(cmd.toCommandArray(), env, logger, new FilePath(tempDir)).join();
if (exitCode != 0)
{
listener.fatalError(CvsTagPublisher.DESCRIPTOR.getDisplayName() + " failed. exit code=" + exitCode);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("IOException occurred: " + e);
return false;
}
catch (InterruptedException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("InterruptedException occurred: " + e);
return false;
}
finally
{
try
{
if (tempDir != null)
{
logger.println("cleaning up " + tempDir);
Util.deleteRecursive(tempDir);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
}
}
return true;
}
/**
* Converts an array into a delimited String
*
* @param array the array to convert
* @param delimiter The delimiter used in the String representation
* @return a delimited String representation of the array
*/
private static String arrayToString(Object array, String delimiter)
{
int length = Array.getLength(array);
if (length == 0)
{
return "";
}
StringBuilder sb = new StringBuilder(2 * length - 1);
for (int i = 0; i < length; i++)
{
if (i > 0)
{
sb.append(delimiter);
}
sb.append(Array.get(array, i));
}
return sb.toString();
}
static String evalGroovyExpression(Map<String, String> env, String expression)
{
Binding binding = new Binding();
binding.setVariable("env", env);
binding.setVariable("sys", System.getProperties());
CompilerConfiguration config = new CompilerConfiguration();
//config.setDebug(true);
GroovyShell shell = new GroovyShell(binding, config);
Object result = shell.evaluate("return \"" + expression + "\"");
if (result == null)
{
return "";
}
else
{
return result.toString().trim();
}
}
}
| true | true | public static boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, String tagName)
{
PrintStream logger = listener.getLogger();
if (!Result.SUCCESS.equals(build.getResult()))
{
logger.println("Skipping CVS Tagging as build result was not successful.");
return true;
}
AbstractProject rootProject = getRootProject(build.getProject());
if (!(rootProject.getScm() instanceof CVSSCM))
{
logger.println("CVS Tag plugin does not support tagging for SCM " + rootProject.getScm() + ".");
return true;
}
CVSSCM scm = CVSSCM.class.cast(rootProject.getScm());
// Evaluate the groovy tag name
Map<String, String> env = build.getEnvVars();
tagName = evalGroovyExpression(env, tagName);
// Get the modules we will be tagging
String modules = arrayToString(scm.getAllModulesNormalized(), " ");
// -D option for rtag command.
// Tag the most recent revision no later than <date> ...
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(build.getTimestamp().getTime());
ArgumentListBuilder cmd = new ArgumentListBuilder();
if (scm.getBranch() != null)
{
// cvs -d cvsRoot rtag -r branchName -D toDate tagName modules
cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-r", scm.getBranch(), "-D", date, tagName, modules);
}
else
{
// cvs -d cvsRoot rtag -D toDate tagName modules
cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-D", date, tagName, modules);
}
logger.println("Executing tag command: " + cmd.toStringWithQuote());
File tempDir = null;
try
{
tempDir = Util.createTempDir();
int exitCode = launcher.launch(cmd.toCommandArray(), env, logger, new FilePath(tempDir)).join();
if (exitCode != 0)
{
listener.fatalError(CvsTagPublisher.DESCRIPTOR.getDisplayName() + " failed. exit code=" + exitCode);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("IOException occurred: " + e);
return false;
}
catch (InterruptedException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("InterruptedException occurred: " + e);
return false;
}
finally
{
try
{
if (tempDir != null)
{
logger.println("cleaning up " + tempDir);
Util.deleteRecursive(tempDir);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
}
}
return true;
}
| public static boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, String tagName)
{
PrintStream logger = listener.getLogger();
if (!Result.SUCCESS.equals(build.getResult()))
{
logger.println("Skipping CVS Tagging as build result was not successful.");
return true;
}
AbstractProject rootProject = getRootProject(build.getProject());
if (!(rootProject.getScm() instanceof CVSSCM))
{
logger.println("CVS Tag plugin does not support tagging for SCM " + rootProject.getScm() + ".");
return true;
}
CVSSCM scm = CVSSCM.class.cast(rootProject.getScm());
// Evaluate the groovy tag name
Map<String, String> env = build.getEnvVars();
tagName = evalGroovyExpression(env, tagName);
// Get the modules we will be tagging
String modules = arrayToString(scm.getAllModulesNormalized(), " ");
// -D option for rtag command.
// Tag the most recent revision no later than <date> ...
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(build.getTimestamp().getTime());
ArgumentListBuilder cmd = new ArgumentListBuilder();
if (scm.getBranch() != null)
{
// cvs -d cvsRoot rtag -r branchName tagName modules
cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-r", scm.getBranch(), tagName, modules);
}
else
{
// cvs -d cvsRoot rtag -D toDate tagName modules
cmd.add(scm.getDescriptor().getCvsExeOrDefault(), "-d", scm.getCvsRoot(), "rtag", "-D", date, tagName, modules);
}
logger.println("Executing tag command: " + cmd.toStringWithQuote());
File tempDir = null;
try
{
tempDir = Util.createTempDir();
int exitCode = launcher.launch(cmd.toCommandArray(), env, logger, new FilePath(tempDir)).join();
if (exitCode != 0)
{
listener.fatalError(CvsTagPublisher.DESCRIPTOR.getDisplayName() + " failed. exit code=" + exitCode);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("IOException occurred: " + e);
return false;
}
catch (InterruptedException e)
{
e.printStackTrace(listener.error(e.getMessage()));
logger.println("InterruptedException occurred: " + e);
return false;
}
finally
{
try
{
if (tempDir != null)
{
logger.println("cleaning up " + tempDir);
Util.deleteRecursive(tempDir);
}
}
catch (IOException e)
{
e.printStackTrace(listener.error(e.getMessage()));
}
}
return true;
}
|
diff --git a/src/main/java/com/conventnunnery/libraries/config/ConventConfigurationManager.java b/src/main/java/com/conventnunnery/libraries/config/ConventConfigurationManager.java
index 7231487..f1cde48 100644
--- a/src/main/java/com/conventnunnery/libraries/config/ConventConfigurationManager.java
+++ b/src/main/java/com/conventnunnery/libraries/config/ConventConfigurationManager.java
@@ -1,70 +1,73 @@
/*
* Copyright (c) 2013. ToppleTheNun
*
* 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 com.conventnunnery.libraries.config;
import org.bukkit.plugin.Plugin;
import java.io.File;
public class ConventConfigurationManager {
private final Plugin plugin;
/**
* Instantiates a new version of the configuration manager for a plugin
*
* @param plugin Plugin that is using the manager
*/
public ConventConfigurationManager(Plugin plugin) {
this.plugin = plugin;
}
public ConventConfiguration loadConventConfiguration(File file) throws IllegalArgumentException {
if (file == null) {
throw new IllegalArgumentException("File cannot be null");
}
ConventConfiguration c = null;
if (file.getName().endsWith(".yml")) {
c = new ConventYamlConfiguration(plugin, file);
}
return c;
}
public ConventConfigurationGroup loadConventConfigurationGroup(File directory) throws IllegalArgumentException {
if (directory == null) {
throw new IllegalArgumentException(directory.getPath() + " cannot be null");
}
+ if (!directory.exists() && directory.getName().endsWith("/")) {
+ directory.mkdirs();
+ }
if (!directory.isDirectory()) {
throw new IllegalArgumentException(directory.getPath() + " must be a directory");
}
if (!directory.exists() && !directory.getParentFile().mkdirs()) {
throw new IllegalArgumentException(directory.getPath() + " does not exist and cannot be made");
}
ConventConfigurationGroup ccg = new ConventConfigurationGroup();
for (File file : directory.listFiles()) {
if (file.getName().endsWith(".yml")) {
ccg.addConventConfiguration(new ConventYamlConfiguration(plugin, file));
}
}
return ccg;
}
}
| true | true | public ConventConfigurationGroup loadConventConfigurationGroup(File directory) throws IllegalArgumentException {
if (directory == null) {
throw new IllegalArgumentException(directory.getPath() + " cannot be null");
}
if (!directory.isDirectory()) {
throw new IllegalArgumentException(directory.getPath() + " must be a directory");
}
if (!directory.exists() && !directory.getParentFile().mkdirs()) {
throw new IllegalArgumentException(directory.getPath() + " does not exist and cannot be made");
}
ConventConfigurationGroup ccg = new ConventConfigurationGroup();
for (File file : directory.listFiles()) {
if (file.getName().endsWith(".yml")) {
ccg.addConventConfiguration(new ConventYamlConfiguration(plugin, file));
}
}
return ccg;
}
| public ConventConfigurationGroup loadConventConfigurationGroup(File directory) throws IllegalArgumentException {
if (directory == null) {
throw new IllegalArgumentException(directory.getPath() + " cannot be null");
}
if (!directory.exists() && directory.getName().endsWith("/")) {
directory.mkdirs();
}
if (!directory.isDirectory()) {
throw new IllegalArgumentException(directory.getPath() + " must be a directory");
}
if (!directory.exists() && !directory.getParentFile().mkdirs()) {
throw new IllegalArgumentException(directory.getPath() + " does not exist and cannot be made");
}
ConventConfigurationGroup ccg = new ConventConfigurationGroup();
for (File file : directory.listFiles()) {
if (file.getName().endsWith(".yml")) {
ccg.addConventConfiguration(new ConventYamlConfiguration(plugin, file));
}
}
return ccg;
}
|
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java
index 57cf3cfa7..77613b526 100644
--- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java
+++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/BugzillaTaskDataHandler.java
@@ -1,738 +1,740 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.bugzilla.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.commons.net.Policy;
import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCustomField.FieldType;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskMapping;
import org.eclipse.mylyn.tasks.core.RepositoryResponse;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataCollector;
import org.eclipse.mylyn.tasks.core.data.TaskMapper;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class BugzillaTaskDataHandler extends AbstractTaskDataHandler {
private enum TaskDataVersion {
VERSION_0(0f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
// ignore
}
},
VERSION_1_0(1.0f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
// 1: the value was stored in the attribute rather than the key
for (TaskAttribute attribute : new ArrayList<TaskAttribute>(data.getRoot().getAttributes().values())) {
if (attribute.getId().equals(BugzillaAttribute.DESC.getKey())) {
TaskAttribute attrLongDesc = createAttribute(data, BugzillaAttribute.LONG_DESC);
attrLongDesc.setValue(attribute.getValue());
data.getRoot().removeAttribute(BugzillaAttribute.DESC.getKey());
}
}
// Old actions not saved so recreate them upon migration
// delete legacy operations:
Set<TaskAttribute> operationsToRemove = new HashSet<TaskAttribute>();
for (TaskAttribute attribute : data.getAttributeMapper().getAttributesByType(data,
TaskAttribute.TYPE_OPERATION)) {
operationsToRemove.add(attribute);
}
for (TaskAttribute taskAttribute : operationsToRemove) {
data.getRoot().removeAttribute(taskAttribute.getId());
}
RepositoryConfiguration configuration = connector.getRepositoryConfiguration(repository.getRepositoryUrl());
if (configuration != null) {
configuration.addValidOperations(data);
}
}
},
VERSION_2_0(2.0f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
updateAttribute(data, BugzillaAttribute.LONG_DESC);
}
},
VERSION_3_0(3.0f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
updateAttribute(data, BugzillaAttribute.NEW_COMMENT);
}
},
VERSION_4_0(4.0f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
updateAttribute(data, BugzillaAttribute.DEADLINE);
updateAttribute(data, BugzillaAttribute.ACTUAL_TIME);
}
},
VERSION_4_1(4.1f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
updateAttribute(data, BugzillaAttribute.VOTES);
TaskAttribute attrDeadline = data.getRoot().getMappedAttribute(BugzillaAttribute.VOTES.getKey());
if (attrDeadline != null) {
attrDeadline.getMetaData().setType(BugzillaAttribute.VOTES.getType());
}
}
},
VERSION_4_2(4.2f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
updateAttribute(data, BugzillaAttribute.CC);
updateAttribute(data, BugzillaAttribute.DEPENDSON);
updateAttribute(data, BugzillaAttribute.BLOCKED);
updateAttribute(data, BugzillaAttribute.BUG_FILE_LOC);
updateAttribute(data, BugzillaAttribute.KEYWORDS);
updateAttribute(data, BugzillaAttribute.STATUS_WHITEBOARD);
updateAttribute(data, BugzillaAttribute.QA_CONTACT);
updateAttribute(data, BugzillaAttribute.NEWCC);
}
},
VERSION_4_3(4.3f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
// migrate custom attributes
for (TaskAttribute attribute : data.getRoot().getAttributes().values()) {
if (attribute.getId().startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) {
attribute.getMetaData().setKind(TaskAttribute.KIND_DEFAULT);
attribute.getMetaData().setReadOnly(false);
if (attribute.getOptions().size() > 0) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
} else {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
}
}
},
VERSION_4_4(4.4f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
// summary didn't have spell checking, update to short rich text
updateAttribute(data, BugzillaAttribute.SHORT_DESC);
}
},
VERSION_4_5(4.5f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
// migrate custom attributes
RepositoryConfiguration configuration = connector.getRepositoryConfiguration(repository.getRepositoryUrl());
if (configuration == null) {
return;
}
for (TaskAttribute attribute : data.getRoot().getAttributes().values()) {
if (attribute.getId().startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) {
BugzillaCustomField customField = null;
String actName = attribute.getId();
for (BugzillaCustomField bugzillaCustomField : configuration.getCustomFields()) {
if (actName.equals(bugzillaCustomField.getName())) {
customField = bugzillaCustomField;
break;
}
}
if (customField != null) {
String desc = customField.getDescription();
attribute.getMetaData().defaults().setLabel(desc).setReadOnly(false);
attribute.getMetaData().setKind(TaskAttribute.KIND_DEFAULT);
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
switch (customField.getFieldType()) {
case FreeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
break;
case DropDown:
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
break;
case MultipleSelection:
attribute.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT);
break;
case LargeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT);
break;
case DateTime:
attribute.getMetaData().setType(TaskAttribute.TYPE_DATETIME);
break;
default:
List<String> options = customField.getOptions();
if (options.size() > 0) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
} else {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
attribute.getMetaData().setReadOnly(false);
}
}
}
}
},
VERSION_CURRENT(4.6f) {
@Override
void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector) {
data.setVersion(TaskDataVersion.VERSION_CURRENT.toString());
}
};
private float versionNumber = 0;
TaskDataVersion(float verNum) {
versionNumber = verNum;
}
public float getVersionNum() {
return versionNumber;
}
abstract void migrate(TaskRepository repository, TaskData data, BugzillaRepositoryConnector connector);
@Override
public String toString() {
return "" + getVersionNum(); //$NON-NLS-1$
}
private static void updateAttribute(TaskData data, BugzillaAttribute bugAttribute) {
TaskAttribute attribute = data.getRoot().getMappedAttribute(bugAttribute.getKey());
if (attribute != null) {
attribute.getMetaData().setType(bugAttribute.getType());
attribute.getMetaData().setReadOnly(bugAttribute.isReadOnly());
attribute.getMetaData().setKind(bugAttribute.getKind());
}
}
}
protected final BugzillaRepositoryConnector connector;
public BugzillaTaskDataHandler(BugzillaRepositoryConnector connector) {
this.connector = connector;
}
public TaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor)
throws CoreException {
Set<String> taskIds = new HashSet<String>();
taskIds.add(taskId);
final TaskData[] retrievedData = new TaskData[1];
TaskDataCollector collector = new TaskDataCollector() {
@Override
public void accept(TaskData taskData) {
retrievedData[0] = taskData;
}
};
getMultiTaskData(repository, taskIds, collector, monitor);
if (retrievedData[0] == null) {
throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
"Task data could not be retrieved. Please re-synchronize task")); //$NON-NLS-1$
}
return retrievedData[0];
// monitor = Policy.monitorFor(monitor);
// try {
// monitor.beginTask("Receiving task", IProgressMonitor.UNKNOWN);
// BugzillaClient client = connector.getClientManager().getClient(repository, monitor);
// int bugId = BugzillaRepositoryConnector.getBugId(taskId);
// TaskData taskData = client.getTaskData(bugId, getAttributeMapper(repository), monitor);
// if (taskData == null) {
// throw new CoreException(new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
// "Task data could not be retrieved. Please re-synchronize task"));
// }
// return taskData;
// } catch (IOException e) {
// throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
// RepositoryStatus.ERROR_IO, repository.getRepositoryUrl(), e));
// } finally {
// monitor.done();
// }
}
@Override
public void getMultiTaskData(final TaskRepository repository, Set<String> taskIds,
final TaskDataCollector collector, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Messages.BugzillaTaskDataHandler_Receiving_tasks, taskIds.size());
BugzillaClient client = connector.getClientManager().getClient(repository, monitor);
final CoreException[] collectionException = new CoreException[1];
class CollectorWrapper extends TaskDataCollector {
private final IProgressMonitor monitor2;
private final TaskDataCollector collector;
@Override
public void failed(String taskId, IStatus status) {
collector.failed(taskId, status);
}
public CollectorWrapper(TaskDataCollector collector, IProgressMonitor monitor2) {
this.collector = collector;
this.monitor2 = monitor2;
}
@Override
public void accept(TaskData taskData) {
try {
initializeTaskData(repository, taskData, null, new SubProgressMonitor(monitor2, 1));
} catch (CoreException e) {
if (collectionException[0] == null) {
collectionException[0] = e;
}
}
collector.accept(taskData);
monitor2.worked(1);
}
}
TaskDataCollector collector2 = new CollectorWrapper(collector, monitor);
client.getTaskData(taskIds, collector2, getAttributeMapper(repository), monitor);
if (collectionException[0] != null) {
throw collectionException[0];
}
} catch (IOException e) {
throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
RepositoryStatus.ERROR_IO, repository.getRepositoryUrl(), e));
} finally {
monitor.done();
}
}
@Override
public void migrateTaskData(TaskRepository taskRepository, TaskData taskData) {
float bugzillaTaskDataVersion = 0;
{
String taskDataVersion = taskData.getVersion();
if (taskDataVersion != null) {
try {
bugzillaTaskDataVersion = Float.parseFloat(taskDataVersion);
} catch (NumberFormatException e) {
bugzillaTaskDataVersion = 0;
}
}
}
for (TaskDataVersion version : TaskDataVersion.values()) {
if (bugzillaTaskDataVersion <= version.getVersionNum()) {
version.migrate(taskRepository, taskData, connector);
}
}
}
@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData,
Set<TaskAttribute> changedAttributes, IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Messages.BugzillaTaskDataHandler_Submitting_task, IProgressMonitor.UNKNOWN);
BugzillaClient client = connector.getClientManager().getClient(repository, monitor);
try {
return client.postTaskData(taskData, monitor);
} catch (CoreException e) {
// TODO: Move retry handling into client
if (e.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) {
return client.postTaskData(taskData, monitor);
} else if (e.getStatus().getCode() == IBugzillaConstants.REPOSITORY_STATUS_SUSPICIOUS_ACTION) {
taskData.getRoot().removeAttribute(BugzillaAttribute.TOKEN.getKey());
return client.postTaskData(taskData, monitor);
} else {
throw e;
}
}
} catch (IOException e) {
throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
RepositoryStatus.ERROR_IO, repository.getRepositoryUrl(), e));
} finally {
monitor.done();
}
}
@Override
public boolean initializeTaskData(TaskRepository repository, TaskData taskData, ITaskMapping initializationData,
IProgressMonitor monitor) throws CoreException {
// Note: setting current version to latest assumes the data arriving here is either for a new task or is
// fresh from the repository (not locally stored data that may not have been migrated).
taskData.setVersion(TaskDataVersion.VERSION_CURRENT.toString());
try {
monitor = Policy.monitorFor(monitor);
monitor.beginTask("Initialize Task Data", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
RepositoryConfiguration repositoryConfiguration = connector.getRepositoryConfiguration(repository, false,
monitor);
if (repositoryConfiguration == null) {
throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
RepositoryStatus.ERROR_REPOSITORY_LOGIN, repository.getRepositoryUrl(),
"Retrieving repository configuration failed.")); //$NON-NLS-1$
}
if (taskData.isNew()) {
String product = null;
String component = null;
if (initializationData == null || initializationData.getProduct() == null) {
if (repositoryConfiguration.getProducts().size() > 0) {
product = repositoryConfiguration.getProducts().get(0);
}
} else {
product = initializationData.getProduct();
}
if (product == null) {
return false;
}
if (initializationData != null && initializationData.getComponent() != null
&& initializationData.getComponent().length() > 0) {
component = initializationData.getComponent();
}
if (component == null && repositoryConfiguration.getComponents(product).size() > 0) {
component = repositoryConfiguration.getComponents(product).get(0);
}
initializeNewTaskDataAttributes(repositoryConfiguration, taskData, product, component, monitor);
if (connector != null) {
connector.setPlatformDefaultsOrGuess(repository, taskData);
}
return true;
} else {
boolean shortLogin = Boolean.parseBoolean(repository.getProperty(IBugzillaConstants.REPOSITORY_SETTING_SHORT_LOGIN));
repositoryConfiguration.configureTaskData(taskData, shortLogin, connector);
}
} finally {
monitor.done();
}
return true;
}
/**
* Only new, unsubmitted task data or freshly received task data from the repository can be passed in here.
*
* @param component
*/
private boolean initializeNewTaskDataAttributes(RepositoryConfiguration repositoryConfiguration, TaskData taskData,
String product, String component, IProgressMonitor monitor) {
TaskAttribute productAttribute = createAttribute(taskData, BugzillaAttribute.PRODUCT);
productAttribute.setValue(product);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
for (String optionValue : optionValues) {
productAttribute.putOption(optionValue, optionValue);
}
TaskAttribute attributeStatus = createAttribute(taskData, BugzillaAttribute.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
attributeStatus.putOption(option, option);
}
attributeStatus.setValue(repositoryConfiguration.getStartStatus());
createAttribute(taskData, BugzillaAttribute.SHORT_DESC);
TaskAttribute attributeVersion = createAttribute(taskData, BugzillaAttribute.VERSION);
optionValues = repositoryConfiguration.getVersions(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeVersion.putOption(option, option);
}
if (optionValues.size() > 0) {
attributeVersion.setValue(optionValues.get(optionValues.size() - 1));
}
TaskAttribute attributeComponent = createAttribute(taskData, BugzillaAttribute.COMPONENT);
optionValues = repositoryConfiguration.getComponents(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeComponent.putOption(option, option);
}
if (optionValues.size() == 1) {
attributeComponent.setValue(optionValues.get(0));
}
if (component != null && optionValues.contains(component)) {
attributeComponent.setValue(component);
}
TaskRepository taskRepository = taskData.getAttributeMapper().getTaskRepository();
String useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
optionValues = repositoryConfiguration.getTargetMilestones(productAttribute.getValue());
if (optionValues.size() > 0) {
TaskAttribute attributeTargetMilestone = createAttribute(taskData, BugzillaAttribute.TARGET_MILESTONE);
for (String option : optionValues) {
attributeTargetMilestone.putOption(option, option);
}
if (repositoryConfiguration != null && product != null && !product.equals("")) { //$NON-NLS-1$
String defaultMilestone = repositoryConfiguration.getDefaultMilestones(product);
if (defaultMilestone != null) {
attributeTargetMilestone.setValue(defaultMilestone);
+ } else {
+ attributeTargetMilestone.setValue(optionValues.get(0));
}
} else {
attributeTargetMilestone.setValue(optionValues.get(0));
}
}
}
TaskAttribute attributePlatform = createAttribute(taskData, BugzillaAttribute.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
attributePlatform.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
attributePlatform.setValue(optionValues.get(0));
}
TaskAttribute attributeOPSYS = createAttribute(taskData, BugzillaAttribute.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
attributeOPSYS.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
attributeOPSYS.setValue(optionValues.get(0));
}
TaskAttribute attributePriority = createAttribute(taskData, BugzillaAttribute.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
attributePriority.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle priority
attributePriority.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeSeverity = createAttribute(taskData, BugzillaAttribute.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
attributeSeverity.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle severity
attributeSeverity.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeAssignedTo = createAttribute(taskData, BugzillaAttribute.ASSIGNED_TO);
attributeAssignedTo.setValue(""); //$NON-NLS-1$
useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
TaskAttribute attributeQAContact = createAttribute(taskData, BugzillaAttribute.QA_CONTACT);
attributeQAContact.setValue(""); //$NON-NLS-1$
}
TaskAttribute attributeBugFileLoc = createAttribute(taskData, BugzillaAttribute.BUG_FILE_LOC);
attributeBugFileLoc.setValue("http://"); //$NON-NLS-1$
createAttribute(taskData, BugzillaAttribute.DEPENDSON);
createAttribute(taskData, BugzillaAttribute.BLOCKED);
createAttribute(taskData, BugzillaAttribute.NEWCC);
createAttribute(taskData, BugzillaAttribute.LONG_DESC);
List<String> keywords = repositoryConfiguration.getKeywords();
if (keywords.size() > 0) {
createAttribute(taskData, BugzillaAttribute.KEYWORDS);
}
TaskAttribute attrDescription = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION);
if (attrDescription != null) {
attrDescription.getMetaData().setReadOnly(false);
}
TaskAttribute attrOwner = taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (attrOwner != null) {
attrOwner.getMetaData().setReadOnly(false);
}
TaskAttribute attrAddSelfToCc = taskData.getRoot().getMappedAttribute(TaskAttribute.ADD_SELF_CC);
if (attrAddSelfToCc != null) {
attrAddSelfToCc.getMetaData().setKind(null);
}
List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
if (repositoryConfiguration != null) {
customFields = repositoryConfiguration.getCustomFields();
}
for (BugzillaCustomField bugzillaCustomField : customFields) {
if (bugzillaCustomField.isEnterBug()) {
List<String> options = bugzillaCustomField.getOptions();
FieldType fieldType = bugzillaCustomField.getFieldType();
if (options.size() < 1
&& (fieldType.equals(FieldType.DropDown) || fieldType.equals(FieldType.MultipleSelection))) {
continue;
}
TaskAttribute attribute = taskData.getRoot().createAttribute(bugzillaCustomField.getName());
if (attribute != null) {
attribute.getMetaData().defaults().setLabel(bugzillaCustomField.getDescription());
attribute.getMetaData().setKind(TaskAttribute.KIND_DEFAULT);
switch (bugzillaCustomField.getFieldType()) {
case FreeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
break;
case DropDown:
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
break;
case MultipleSelection:
attribute.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT);
break;
case LargeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT);
break;
case DateTime:
attribute.getMetaData().setType(TaskAttribute.TYPE_DATETIME);
break;
default:
if (options.size() > 0) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
} else {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
attribute.getMetaData().setReadOnly(false);
for (String option : options) {
attribute.putOption(option, option);
}
if (bugzillaCustomField.getFieldType() == BugzillaCustomField.FieldType.DropDown
&& options.size() > 0) {
attribute.setValue(options.get(0));
}
}
}
}
return true;
}
@Override
public boolean canGetMultiTaskData(TaskRepository taskRepository) {
return true;
}
@Override
public boolean canInitializeSubTaskData(TaskRepository taskRepository, ITask task) {
return true;
}
@Override
public boolean initializeSubTaskData(TaskRepository repository, TaskData subTaskData, TaskData parentTaskData,
IProgressMonitor monitor) throws CoreException {
TaskMapper mapper = new TaskMapper(parentTaskData);
initializeTaskData(repository, subTaskData, mapper, monitor);
new TaskMapper(subTaskData).merge(mapper);
subTaskData.getRoot().getMappedAttribute(BugzillaAttribute.DEPENDSON.getKey()).setValue(""); //$NON-NLS-1$
subTaskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION).setValue(""); //$NON-NLS-1$
subTaskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY).setValue(""); //$NON-NLS-1$
TaskAttribute keywords = subTaskData.getRoot().getMappedAttribute(TaskAttribute.KEYWORDS);
if (keywords != null) {
// only if the repository has keywords this attribut exists
keywords.setValue(""); //$NON-NLS-1$
}
subTaskData.getRoot().getAttribute(BugzillaAttribute.BLOCKED.getKey()).setValue(parentTaskData.getTaskId());
TaskAttribute parentAttributeAssigned = parentTaskData.getRoot()
.getMappedAttribute(TaskAttribute.USER_ASSIGNED);
subTaskData.getRoot()
.getAttribute(BugzillaAttribute.ASSIGNED_TO.getKey())
.setValue(parentAttributeAssigned.getValue());
return true;
}
@Override
public TaskAttributeMapper getAttributeMapper(TaskRepository taskRepository) {
return new BugzillaAttributeMapper(taskRepository, connector);
}
public static TaskAttribute createAttribute(TaskData data, BugzillaAttribute key) {
return createAttribute(data.getRoot(), key);
}
public static TaskAttribute createAttribute(TaskAttribute parent, BugzillaAttribute key) {
TaskAttribute attribute = parent.createAttribute(key.getKey());
attribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
return attribute;
}
public void postUpdateAttachment(TaskRepository repository, TaskAttribute taskAttribute, String action,
IProgressMonitor monitor) throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask(Messages.BugzillaTaskDataHandler_updating_attachment, IProgressMonitor.UNKNOWN);
BugzillaClient client = connector.getClientManager().getClient(repository, monitor);
try {
client.postUpdateAttachment(taskAttribute, action, monitor);
} catch (CoreException e) {
// TODO: Move retry handling into client
if (e.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) {
AuthenticationCredentials creds = repository.getCredentials(AuthenticationType.REPOSITORY);
if (creds != null && creds.getUserName() != null && creds.getUserName().length() > 0) {
client.postUpdateAttachment(taskAttribute, action, monitor);
} else {
throw e;
}
} else {
throw e;
}
}
} catch (IOException e) {
throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
RepositoryStatus.ERROR_IO, repository.getRepositoryUrl(), e));
} finally {
monitor.done();
}
}
}
| true | true | private boolean initializeNewTaskDataAttributes(RepositoryConfiguration repositoryConfiguration, TaskData taskData,
String product, String component, IProgressMonitor monitor) {
TaskAttribute productAttribute = createAttribute(taskData, BugzillaAttribute.PRODUCT);
productAttribute.setValue(product);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
for (String optionValue : optionValues) {
productAttribute.putOption(optionValue, optionValue);
}
TaskAttribute attributeStatus = createAttribute(taskData, BugzillaAttribute.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
attributeStatus.putOption(option, option);
}
attributeStatus.setValue(repositoryConfiguration.getStartStatus());
createAttribute(taskData, BugzillaAttribute.SHORT_DESC);
TaskAttribute attributeVersion = createAttribute(taskData, BugzillaAttribute.VERSION);
optionValues = repositoryConfiguration.getVersions(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeVersion.putOption(option, option);
}
if (optionValues.size() > 0) {
attributeVersion.setValue(optionValues.get(optionValues.size() - 1));
}
TaskAttribute attributeComponent = createAttribute(taskData, BugzillaAttribute.COMPONENT);
optionValues = repositoryConfiguration.getComponents(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeComponent.putOption(option, option);
}
if (optionValues.size() == 1) {
attributeComponent.setValue(optionValues.get(0));
}
if (component != null && optionValues.contains(component)) {
attributeComponent.setValue(component);
}
TaskRepository taskRepository = taskData.getAttributeMapper().getTaskRepository();
String useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
optionValues = repositoryConfiguration.getTargetMilestones(productAttribute.getValue());
if (optionValues.size() > 0) {
TaskAttribute attributeTargetMilestone = createAttribute(taskData, BugzillaAttribute.TARGET_MILESTONE);
for (String option : optionValues) {
attributeTargetMilestone.putOption(option, option);
}
if (repositoryConfiguration != null && product != null && !product.equals("")) { //$NON-NLS-1$
String defaultMilestone = repositoryConfiguration.getDefaultMilestones(product);
if (defaultMilestone != null) {
attributeTargetMilestone.setValue(defaultMilestone);
}
} else {
attributeTargetMilestone.setValue(optionValues.get(0));
}
}
}
TaskAttribute attributePlatform = createAttribute(taskData, BugzillaAttribute.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
attributePlatform.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
attributePlatform.setValue(optionValues.get(0));
}
TaskAttribute attributeOPSYS = createAttribute(taskData, BugzillaAttribute.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
attributeOPSYS.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
attributeOPSYS.setValue(optionValues.get(0));
}
TaskAttribute attributePriority = createAttribute(taskData, BugzillaAttribute.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
attributePriority.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle priority
attributePriority.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeSeverity = createAttribute(taskData, BugzillaAttribute.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
attributeSeverity.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle severity
attributeSeverity.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeAssignedTo = createAttribute(taskData, BugzillaAttribute.ASSIGNED_TO);
attributeAssignedTo.setValue(""); //$NON-NLS-1$
useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
TaskAttribute attributeQAContact = createAttribute(taskData, BugzillaAttribute.QA_CONTACT);
attributeQAContact.setValue(""); //$NON-NLS-1$
}
TaskAttribute attributeBugFileLoc = createAttribute(taskData, BugzillaAttribute.BUG_FILE_LOC);
attributeBugFileLoc.setValue("http://"); //$NON-NLS-1$
createAttribute(taskData, BugzillaAttribute.DEPENDSON);
createAttribute(taskData, BugzillaAttribute.BLOCKED);
createAttribute(taskData, BugzillaAttribute.NEWCC);
createAttribute(taskData, BugzillaAttribute.LONG_DESC);
List<String> keywords = repositoryConfiguration.getKeywords();
if (keywords.size() > 0) {
createAttribute(taskData, BugzillaAttribute.KEYWORDS);
}
TaskAttribute attrDescription = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION);
if (attrDescription != null) {
attrDescription.getMetaData().setReadOnly(false);
}
TaskAttribute attrOwner = taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (attrOwner != null) {
attrOwner.getMetaData().setReadOnly(false);
}
TaskAttribute attrAddSelfToCc = taskData.getRoot().getMappedAttribute(TaskAttribute.ADD_SELF_CC);
if (attrAddSelfToCc != null) {
attrAddSelfToCc.getMetaData().setKind(null);
}
List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
if (repositoryConfiguration != null) {
customFields = repositoryConfiguration.getCustomFields();
}
for (BugzillaCustomField bugzillaCustomField : customFields) {
if (bugzillaCustomField.isEnterBug()) {
List<String> options = bugzillaCustomField.getOptions();
FieldType fieldType = bugzillaCustomField.getFieldType();
if (options.size() < 1
&& (fieldType.equals(FieldType.DropDown) || fieldType.equals(FieldType.MultipleSelection))) {
continue;
}
TaskAttribute attribute = taskData.getRoot().createAttribute(bugzillaCustomField.getName());
if (attribute != null) {
attribute.getMetaData().defaults().setLabel(bugzillaCustomField.getDescription());
attribute.getMetaData().setKind(TaskAttribute.KIND_DEFAULT);
switch (bugzillaCustomField.getFieldType()) {
case FreeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
break;
case DropDown:
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
break;
case MultipleSelection:
attribute.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT);
break;
case LargeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT);
break;
case DateTime:
attribute.getMetaData().setType(TaskAttribute.TYPE_DATETIME);
break;
default:
if (options.size() > 0) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
} else {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
attribute.getMetaData().setReadOnly(false);
for (String option : options) {
attribute.putOption(option, option);
}
if (bugzillaCustomField.getFieldType() == BugzillaCustomField.FieldType.DropDown
&& options.size() > 0) {
attribute.setValue(options.get(0));
}
}
}
}
return true;
}
| private boolean initializeNewTaskDataAttributes(RepositoryConfiguration repositoryConfiguration, TaskData taskData,
String product, String component, IProgressMonitor monitor) {
TaskAttribute productAttribute = createAttribute(taskData, BugzillaAttribute.PRODUCT);
productAttribute.setValue(product);
List<String> optionValues = repositoryConfiguration.getProducts();
Collections.sort(optionValues);
for (String optionValue : optionValues) {
productAttribute.putOption(optionValue, optionValue);
}
TaskAttribute attributeStatus = createAttribute(taskData, BugzillaAttribute.BUG_STATUS);
optionValues = repositoryConfiguration.getStatusValues();
for (String option : optionValues) {
attributeStatus.putOption(option, option);
}
attributeStatus.setValue(repositoryConfiguration.getStartStatus());
createAttribute(taskData, BugzillaAttribute.SHORT_DESC);
TaskAttribute attributeVersion = createAttribute(taskData, BugzillaAttribute.VERSION);
optionValues = repositoryConfiguration.getVersions(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeVersion.putOption(option, option);
}
if (optionValues.size() > 0) {
attributeVersion.setValue(optionValues.get(optionValues.size() - 1));
}
TaskAttribute attributeComponent = createAttribute(taskData, BugzillaAttribute.COMPONENT);
optionValues = repositoryConfiguration.getComponents(productAttribute.getValue());
Collections.sort(optionValues);
for (String option : optionValues) {
attributeComponent.putOption(option, option);
}
if (optionValues.size() == 1) {
attributeComponent.setValue(optionValues.get(0));
}
if (component != null && optionValues.contains(component)) {
attributeComponent.setValue(component);
}
TaskRepository taskRepository = taskData.getAttributeMapper().getTaskRepository();
String useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
optionValues = repositoryConfiguration.getTargetMilestones(productAttribute.getValue());
if (optionValues.size() > 0) {
TaskAttribute attributeTargetMilestone = createAttribute(taskData, BugzillaAttribute.TARGET_MILESTONE);
for (String option : optionValues) {
attributeTargetMilestone.putOption(option, option);
}
if (repositoryConfiguration != null && product != null && !product.equals("")) { //$NON-NLS-1$
String defaultMilestone = repositoryConfiguration.getDefaultMilestones(product);
if (defaultMilestone != null) {
attributeTargetMilestone.setValue(defaultMilestone);
} else {
attributeTargetMilestone.setValue(optionValues.get(0));
}
} else {
attributeTargetMilestone.setValue(optionValues.get(0));
}
}
}
TaskAttribute attributePlatform = createAttribute(taskData, BugzillaAttribute.REP_PLATFORM);
optionValues = repositoryConfiguration.getPlatforms();
for (String option : optionValues) {
attributePlatform.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 choose first platform: All
attributePlatform.setValue(optionValues.get(0));
}
TaskAttribute attributeOPSYS = createAttribute(taskData, BugzillaAttribute.OP_SYS);
optionValues = repositoryConfiguration.getOSs();
for (String option : optionValues) {
attributeOPSYS.putOption(option, option);
}
if (optionValues.size() > 0) {
// bug 159397 change to choose first op_sys All
attributeOPSYS.setValue(optionValues.get(0));
}
TaskAttribute attributePriority = createAttribute(taskData, BugzillaAttribute.PRIORITY);
optionValues = repositoryConfiguration.getPriorities();
for (String option : optionValues) {
attributePriority.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle priority
attributePriority.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeSeverity = createAttribute(taskData, BugzillaAttribute.BUG_SEVERITY);
optionValues = repositoryConfiguration.getSeverities();
for (String option : optionValues) {
attributeSeverity.putOption(option, option);
}
if (optionValues.size() > 0) {
// choose middle severity
attributeSeverity.setValue(optionValues.get((optionValues.size() / 2)));
}
TaskAttribute attributeAssignedTo = createAttribute(taskData, BugzillaAttribute.ASSIGNED_TO);
attributeAssignedTo.setValue(""); //$NON-NLS-1$
useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT);
if (useParam != null && useParam.equals("true")) { //$NON-NLS-1$
TaskAttribute attributeQAContact = createAttribute(taskData, BugzillaAttribute.QA_CONTACT);
attributeQAContact.setValue(""); //$NON-NLS-1$
}
TaskAttribute attributeBugFileLoc = createAttribute(taskData, BugzillaAttribute.BUG_FILE_LOC);
attributeBugFileLoc.setValue("http://"); //$NON-NLS-1$
createAttribute(taskData, BugzillaAttribute.DEPENDSON);
createAttribute(taskData, BugzillaAttribute.BLOCKED);
createAttribute(taskData, BugzillaAttribute.NEWCC);
createAttribute(taskData, BugzillaAttribute.LONG_DESC);
List<String> keywords = repositoryConfiguration.getKeywords();
if (keywords.size() > 0) {
createAttribute(taskData, BugzillaAttribute.KEYWORDS);
}
TaskAttribute attrDescription = taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION);
if (attrDescription != null) {
attrDescription.getMetaData().setReadOnly(false);
}
TaskAttribute attrOwner = taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (attrOwner != null) {
attrOwner.getMetaData().setReadOnly(false);
}
TaskAttribute attrAddSelfToCc = taskData.getRoot().getMappedAttribute(TaskAttribute.ADD_SELF_CC);
if (attrAddSelfToCc != null) {
attrAddSelfToCc.getMetaData().setKind(null);
}
List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
if (repositoryConfiguration != null) {
customFields = repositoryConfiguration.getCustomFields();
}
for (BugzillaCustomField bugzillaCustomField : customFields) {
if (bugzillaCustomField.isEnterBug()) {
List<String> options = bugzillaCustomField.getOptions();
FieldType fieldType = bugzillaCustomField.getFieldType();
if (options.size() < 1
&& (fieldType.equals(FieldType.DropDown) || fieldType.equals(FieldType.MultipleSelection))) {
continue;
}
TaskAttribute attribute = taskData.getRoot().createAttribute(bugzillaCustomField.getName());
if (attribute != null) {
attribute.getMetaData().defaults().setLabel(bugzillaCustomField.getDescription());
attribute.getMetaData().setKind(TaskAttribute.KIND_DEFAULT);
switch (bugzillaCustomField.getFieldType()) {
case FreeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
break;
case DropDown:
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
break;
case MultipleSelection:
attribute.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT);
break;
case LargeText:
attribute.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT);
break;
case DateTime:
attribute.getMetaData().setType(TaskAttribute.TYPE_DATETIME);
break;
default:
if (options.size() > 0) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT);
} else {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
attribute.getMetaData().setReadOnly(false);
for (String option : options) {
attribute.putOption(option, option);
}
if (bugzillaCustomField.getFieldType() == BugzillaCustomField.FieldType.DropDown
&& options.size() > 0) {
attribute.setValue(options.get(0));
}
}
}
}
return true;
}
|
diff --git a/Tarsus/src/java/GameInstance.java b/Tarsus/src/java/GameInstance.java
index bac5480..4f3952a 100644
--- a/Tarsus/src/java/GameInstance.java
+++ b/Tarsus/src/java/GameInstance.java
@@ -1,2899 +1,2899 @@
/*******************************************************
* Class for game instances, will be associated with
* sessions through being the session data.
*******************************************************/
import database.DBConnections;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.ArrayList;
//Pulled from inclass exmple
import database.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GameInstance {
PlayerCharacter playerChar;
AresCharacter aresChar;
stateEnum currentState, startingState;
String accountName;
DBConnections dataSource = null;
Connection conn = null;
Statement stat = null;
final int STORE_SIZE = 20;
int gold;
String error;
int storeLevel;
Item[] storeItems;
String item_type_string[] = {"Error", "Weapon", "Armor", "Item"};
final int constantPtsPerLevel = 5;
final int constantWeaponPtsPerLevel = 3;
final int constantArmorPtsPerLevel = 5;
final int constantGoldPerLevel = 20;
final int constantHealthPerLevel = 15;
final int constantStrengthPerLevel = 5;
final int constantAgilityPerLevel = 5;
final int constantMagicPerLevel = 5;
final int constantHealthBase = 100;
final int constantItemNameMaxLength = 20;
final double constantItemScalar = .75;
GameInstance()
{
playerChar = null;
aresChar = null;
currentState = stateEnum.INIT;
accountName = "Unregistered User";
gold = 0;
error = null;
int storeLevel = 0;
Item[] storeItems = new Item[STORE_SIZE];
}
/****************************************************
* Connect to the database using class variables
* SQL Commands
***************************************************/
void connectDB(){
dataSource = DBConnections.getInstance();
conn = dataSource.getConnection();
}
/****************************************************
* Disconnect from the database using class variables
* SQL Commands
***************************************************/
void disconnectDB(){
DBUtilities.closeStatement(stat);
dataSource.freeConnection(conn);
}
/****************************************************
* Returns the result set result of your query
* @param query the SQL query you want to execute
* @param out the printwriter
***************************************************/
ResultSet sqlQuery(String query, PrintWriter out){
ResultSet result = null;
try{
stat = conn.createStatement();
result = stat.executeQuery(query);
}catch(Exception ex){
out.println("Query error:");
out.println(ex);
}finally{
return result;
}
}
/****************************************************
* Returns true if your SQL command succeeded,
* returns false if it does not
* @param command the SQL command you want to execute
* @param out the printwriter
***************************************************/
Boolean sqlCommand(String command, PrintWriter out){
Boolean result = false;
try{
stat = conn.createStatement();
stat.execute(command);
result = true;
}catch(Exception ex){
out.println("sqlCommand Exception: ");
out.println(ex);
}finally{
return result;
}
}
/****************************************************
* state machine case switch function, called from
* the servlet.
* @param out output PrintWriter
* @param request the servlet request
***************************************************/
void advanceGame(PrintWriter out, HttpServletRequest request)
{
stateEnum nextState = currentState;
startingState = currentState;
do
{
currentState = nextState;
switch(currentState)
{
case INIT:
//first connection
nextState = initState(out, request);
break;
case BATTLE:
//battle function
nextState = battleState(out, request);
break;
case STORE:
//store function
nextState = storeState(out, request);
break;
case REGISTERED_CHARACTER_CREATION:
//character creation
nextState = registeredCharacterCreationState(out, request);
break;
case UNREGISTERED_CHARACTER_CREATION:
//character creation
nextState = unregisteredCharacterCreationState(out, request);
break;
case DECISION:
//this state is for asking what to do next
nextState = decisionState(out, request);
break;
case BLACKSMITH:
//upgrade items
nextState = blackSmithState(out, request);
break;
case LOGIN:
//login
nextState = loginState(out, request);
break;
case ACCOUNT_CREATION:
//account creation
try{
nextState = accountCreation(out, request);}
catch(SQLException ex)
{
out.println("What the ");
out.println(ex);
}
break;
case LEVEL_UP:
nextState = levelUpState(out, request);
break;
case PROFILE:
//profile
try{
nextState = profileState(out, request);}
catch(SQLException ex)
{
out.println("What the ");
out.println(ex);
}
break;
case PAST_CHARACTERS:
//Look at Past Characters
nextState = pastCharactersState(out, request);
break;
case ALL_CHARACTERS:
// look at all Characters
nextState = allCharactersState(out, request);
break;
case LOGOUT:
//Log Out
nextState = LogoutState(out, request);
break;
default:
//this should go to a specified state
nextState = stateEnum.INIT;
initState(out, request);
break;
}
}while((currentState != nextState)|(error!=null));
}
/****************************************************
* Generates an inventory for the store based on the
* player character's level
* @param level the level of the player character
* @return an array of new items for the store
***************************************************/
Item[] getStoreInventory(int level, int size)
{
final int STORE_LEVEL = level;
final int STORE_SIZE = size;
Item[] storeItems = new Item[STORE_SIZE];
for(int i = 0; i < STORE_SIZE; i++)
{
//general type index that decides one of the three
// item types. // not including error
int gi = (int)(Math.round(Math.random() * (2)) + 1);
storeItems[i] = generateItem(gi, STORE_LEVEL);
}
return storeItems;
}
Item generateItem(int type, int Level)
{
final String[] armor_name_type = {"Plate Armor", "Leather Armor", "Robe", "Mail Armor", "Magic Strength armor", "Magic Agility armor", "Armor"};
final String[] weapon_name_type = {"Sword", "Axe", "Mace", "Bow", "Crossbow", "Throwing Knives", "Staff", "Wand", "Orb"}; // Could have room for permutations
final String[] item_name_type = {"Potion"};
final String[] error_name_type = {"Error"};
final String[] item_name_quality_description = {"Broken", "Inferior", "Common", "Slightly Better", "Ancient", "Legendary", "Actually Broken"};
final String[][] general_item_type = {error_name_type, weapon_name_type, armor_name_type, item_name_type};
//final String[] item_name_Modifier_description = ["Warrior", "Hunter", "Wizard", "Bandit", "BattleMage", "Magic-Range Thing whatever", "Balance"] // permutation for each thing
double base_stats[] = {0, 0, 0, 0};
//general type index
int gi = type;
//System.out.println(gi);
// special type index
int si = (int)(Math.round(Math.random() * (general_item_type[gi].length - 1)));
//System.out.println(si);
// armor case
if(gi == 2)
{
switch (si)
{
case 0: base_stats[0] = 1;
base_stats[1] = 0;
base_stats[2] = 0;
break;
case 1: base_stats[0] = 0;
base_stats[1] = 1;
base_stats[2] = 0;
break;
case 2: base_stats[0] = 0;
base_stats[1] = 0;
base_stats[2] = 1;
break;
case 3: base_stats[0] = .5;
base_stats[1] = .5;
base_stats[2] = 0;
break;
case 4: base_stats[0] = .5;
base_stats[1] = 0;
base_stats[2] = .5;
break;
case 5: base_stats[0] = 0;
base_stats[1] = .5;
base_stats[2] = .5;
break;
case 6: base_stats[0] = 0.3333;
base_stats[1] = 0.3333;
base_stats[2] = 0.3333;
break;
}
}
// weapon case
else if(gi == 1)
{
if((si % 9) < 3)
{
base_stats[0] = 1;
}
else if((si % 9) < 6)
{
base_stats[1] = 1;
}
else if((si % 9) < 9)
{
base_stats[2] = 1;
}
}
// item case
else if(gi == 3)
{
switch(si)
{
// potions have an abitrary larger base value thing
case 0: base_stats[3] = 2;
break;
}
}
// Higher levels will have a more balance distribution of items
// e.g. Cannot possibly find a legendary item until at least level 9
double quality = getQuality(Level);
int index = (int) Math.round(quality * ((item_name_quality_description.length) - 1));
String item_quality = item_name_quality_description[index];
String item_type = general_item_type[gi][si];
// Get the base damage of each stat
// will only affect one stat at the moment
//int value_sum = 0;
for(int j = 0; j < 4; j++)
{
// multiples the base stat for cases where the base stat is split up in proportions
base_stats[j] *=(((quality) * 100) + 20) * constantItemScalar; // apply some constant e.g .75
base_stats[j] = Math.round(base_stats[j]);
//value_sum += base_stats[j];
}
String item_name = item_quality + " " + item_type;
Item item = new Item(item_name, 0, gi, 0, (int)base_stats[0], (int)base_stats[1],(int)base_stats[2], (int)base_stats[3]);
return item;
}
/****************************************************
* Generates an armor item based on the player
* character's level
* @param level the level of the player character
* @return an item with a type of armor
***************************************************/
Item generateArmor(int level)
{
return generateItem(2, level);
}
/****************************************************
* Generates a weapon item based on the player
* character's level
* @param level the level of the player character
* @return an item with a type of weapon
***************************************************/
Item generateWeapon(int level)
{
return generateItem(1,level);
}
/****************************************************
* Loads a new enemy from the database
* @param level the players level
***************************************************/
void getNextEnemy(Integer Level, PrintWriter out) throws SQLException
{
//this gets all of the characters at a given level
String search1 = "SELECT * FROM Characters WHERE level='"+Level.toString() + "' AND isDead=b'1';";
connectDB();
//this will get the number of characters at a given level
String maxCount = "SELECT COUNT(*) AS rows FROM Characters WHERE level='1' AND isDead=b'1';";
ResultSet resultMax = sqlQuery(maxCount, out);
resultMax.next();
int max = resultMax.getInt("rows");
disconnectDB();
connectDB();
ResultSet result = sqlQuery(search1, out);
//get a random number between 1 and the total number of characters, for selecting an enemy
int number = (int) (Math.random()*max) +1;
if(result.isBeforeFirst())
{
//iterate to the enemy randomly selected
for(int i=0;i<number;i++)
{
result.next();
}
if(result.isAfterLast())
result.last();
//get the information about the character and reduce all stats to 90%
String name = result.getString("name");
String bio = result.getString("bio");
int level = result.getInt("level");
int health = (int) (result.getInt("health")*.9);
int strength = (int) (result.getInt("strength")*.9);
int agility = (int) (result.getInt("agility")*.9);
int magic = (int) (result.getInt("magic")*.9);
int timesAttacked = result.getInt("timesAttacked");
int timesSwitchedToStrength = result.getInt("timesSwitchedToStrength");
int timesSwitchedToAgility = result.getInt("timesSwitchedToAgility");
int timesSwitchedToMagic = result.getInt("timesSwitchedToMagic");
int equipWeaponId = result.getInt("equippedWeapon");
int equipArmorId = result.getInt("equippedArmor");
disconnectDB();
//getting the length for itemsHeld
connectDB();
String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';";
result = sqlQuery(search2, out);
result.next();
int rows = result.getInt("rows");
disconnectDB();
//load the items held
Item[] itemsHeld = new Item[rows];
Item weapon = null;
Item armor = null;
String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';";
connectDB();
result = sqlQuery(search3, out);
//temp varible
int i = 0;
while (result.next())
{
String iName = result.getString("name");
int itemId = result.getInt("itemId");
int type = result.getInt("type");
int upgradeCount = result.getInt("upgradeCount");
int strengthVal= result.getInt("strengthVal");
int agilityVal = result.getInt("agilityVal");
int magicVal = result.getInt("magicVal");
Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0);
itemsHeld[i] = item;
if (equipWeaponId == itemId)
{
weapon = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0);
}
if (equipArmorId == itemId)
{
armor = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0);
}
i++;
}
disconnectDB();
aresChar = new AresCharacter(name, bio, level, health, strength, agility, magic, itemsHeld, weapon, armor, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic);
}
else
{
//if there are no characters at the level, generate Ares who is very hard to beat
Item[] itemsHeld = {generateWeapon(Level +1), generateArmor(Level+1)};
int aresHealth = constantHealthBase+(Level+1)*constantPtsPerLevel*constantHealthPerLevel;
int aresStrength = (Level+1)*constantPtsPerLevel*constantStrengthPerLevel;
int aresAgility = (Level+1)*constantPtsPerLevel*constantAgilityPerLevel;
int aresMagic = (Level+1)*constantPtsPerLevel*constantMagicPerLevel;
aresChar = new AresCharacter("Ares", "", Level, aresHealth, aresStrength, aresAgility, aresMagic, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0);
}
}
/****************************************************
* Loads the players current character from the
* database
***************************************************/
void getCurrentCharacter()
{
}
/****************************************************
* Adds a newly created character to the database
* diconnectDB needs to be called after use
* @param chrct character object to add to the database
* @param isDead Boolean, whether or not the character is dead
* @param out PrintWriter for the page
* @return did it work
***************************************************/
Boolean newCharacter(Character chrct, Boolean isDead, PrintWriter out)
{
Integer dead=0;
if(isDead)
dead=1;
connectDB();
String query = "INSERT into Characters (name, level, bio, creator, strength, health, isDead, magic, agility, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic, equippedWeapon, equippedArmor) VALUES ('"+chrct.getName()+"', '"+(((Integer)chrct.getLevel()).toString())+"', '"+chrct.getBio()+"', '"+accountName+"', '"+((Integer)(chrct.getStrength())).toString()+"', '"+((Integer)chrct.getMaxHealth()).toString()+"', b'"+dead.toString()+"', '"+((Integer)chrct.getMagic()).toString()+"', '"+((Integer)chrct.getAgility()).toString()+"', '"+((Integer)chrct.timesAttacked).toString()+"', '"+((Integer)chrct.timesSwitchedToStrength).toString()+"', '"+((Integer)chrct.timesSwitchedToAgility).toString()+"', '"+((Integer)chrct.timesSwitchedToMagic).toString()+"', '"+((Integer)chrct.weapon.getItemId()).toString()+"', '"+((Integer)chrct.armor.getItemId()).toString()+"');";
return sqlCommand(query,out);
}
/****************************************************
* Update created character to the database
* disconnectDB needs to be called after use
* @param chrct character object to update in the database
* @param isDead Boolean, whether or not the character is dead
* @param out PrintWriter for the page
* @return did it work
***************************************************/
Boolean updateCharacter(Character chrct, Boolean isDead, PrintWriter out)
{
Integer dead=0;
if(isDead)
dead=1;
connectDB();
String query = "UPDATE Characters SET level='"+(((Integer)chrct.getLevel()).toString())+"', bio='"+chrct.getBio()+"', strength='"+((Integer)(chrct.getStrength())).toString()+"', health='"+((Integer)chrct.getMaxHealth()).toString()+"', isDead=b'"+(dead.toString())+"', magic='"+((Integer)chrct.getMagic()).toString()+"', agility='"+((Integer)chrct.getAgility()).toString()+"', timesAttacked='"+((Integer)chrct.timesAttacked).toString()+"', timesSwitchedToStrength='"+((Integer)chrct.timesSwitchedToStrength).toString()+"', timesSwitchedToAgility='"+((Integer)chrct.timesSwitchedToAgility).toString()+"', timesSwitchedToMagic='"+((Integer)chrct.timesSwitchedToMagic).toString()+"', equippedWeapon='"+((Integer)chrct.weapon.getItemId()).toString()+"', equippedArmor='"+((Integer)chrct.armor.getItemId()).toString()+"' WHERE name='"+chrct.getName()+"';";
return sqlCommand(query,out);
}
/****************************************************
* Adds new item to the database
* disconnectDB needs to be called after use
* @param item item object to add to the database
* @param out PrintWriter for the page
* @return did it work
***************************************************/
Boolean newItem(Item item, PrintWriter out) throws SQLException
{
if(item.getItemId()==0)
item.itemId=nextItemId(out);
connectDB();
String query = "Insert into Items (itemId, name, type, strengthVal, healthVal, upgradeCount, magicVal, agilityVal) VALUES ('"+((Integer)item.getItemId()).toString()+"', '"+item.getName()+"', '"+((Integer)item.getType()).toString()+"', '"+((Integer)item.getStrength()).toString()+"', '"+((Integer)item.getHeal()).toString()+"', '"+((Integer)item.getUpgradeCount()).toString()+"', '"+((Integer)item.getMagic()).toString()+"', '"+((Integer)item.getAgility()).toString()+"');";
return sqlCommand(query,out);
}
Boolean deleteCharacterHasItem(Item item, PrintWriter out) throws SQLException
{
//String query = "DELETE FROM CharacterHasItem WHERE itemID=";
String query = "DELETE FROM CharacterHasItem WHERE itemId=";
query += "" + item.getItemId() + "";
query += ";";
return sqlCommand(query, out);
}
Boolean deleteItem(Item item, PrintWriter out) throws SQLException
{
deleteCharacterHasItem(item, out);
String query = "DELETE FROM Items WHERE itemId=";
query += "" + item.getItemId() + "";
query += ";";
return sqlCommand(query, out);
}
int nextItemId(PrintWriter out) throws SQLException
{
String query="SELECT * FROM Items;";
int max = 0;
connectDB();
ResultSet result = sqlQuery(query, out);
while(result.next()){
if(result.getInt("itemId")>max)
max=result.getInt("itemId");
}
disconnectDB();
return max+1;
}
Boolean characterHasItem(Item item, Character character,PrintWriter out)
{
String query = "INSERT into CharacterHasItem (itemId, charName) VALUES ('"+item.getItemId()+"','"+character.getName()+"');";
return sqlCommand(query, out);
}
/****************************************************
* The initial state
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum initState(PrintWriter out, HttpServletRequest request) {
//can log in or unregistered user creation
if(startingState != stateEnum.INIT)
{
//print the page
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input href=\"index.html\" id=\"tarsusTitle\" /> \n" +
" <input class=\"button\" type=\"submit\" value=\"Log In\" name=\"Log In\" /> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Welcome</h1>\n" +
" <p align=\"justify\"> \n" +
" Tarsus is a web based Role Playing Game that allows you to create your own character and use it to fight progressively more difficult enemies as you try to make your way to the top. If you already have an account, click the Log In button above. If not, you can make a character using our character maker or your can sign up and start your own adventure.\n" +
" </p>\n" +
" <div align=\"center\">\n" +
" <input type=\"submit\" value=\"Create a Character\" name=\"Create a Character\" class=frontPageButton />\n" +
" <input type=\"submit\" value=\"Sign Up\" name=\"Sign Up\" class=frontPageButton />\n" +
" </div>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>\n" +
" </body>\n" +
" \n" +
"</html>");
return stateEnum.INIT;
}
else
{
String value1 = request.getParameter("Sign Up");
String value2 = request.getParameter("Log In");
String value3 = request.getParameter("Create a Character");
String value = "";
if(value1 != null)
value = value1;
if(value2!=null)
value = value2;
if(value3!=null)
value = value3;
if(value.equals("Log In"))
return stateEnum.LOGIN;
if(value.equals("Create a Character"))
return stateEnum.UNREGISTERED_CHARACTER_CREATION;
if(value.equals("Sign Up"))
return stateEnum.ACCOUNT_CREATION;
}
return stateEnum.INIT;
}
/****************************************************
* The initial state
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
private stateEnum storeState(PrintWriter out, HttpServletRequest request) {
// have store level as well as the items be static so that it is the same each time the player comes back to the
// store unless the player has increased in level
// if level has changed create a new item inventory for the store
// based on some hash function of the character's level
if(playerChar.getLevel() != storeLevel)
{
storeLevel = playerChar.getLevel();
storeItems = getStoreInventory(storeLevel, STORE_SIZE);
}
if(startingState != stateEnum.STORE)
{
printStoreState(out);
return stateEnum.STORE;
}
else{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
if(value1 != null)
{
return stateEnum.DECISION;
}
else if(value2 != null)
{
return stateEnum.LOGOUT;
}
else
{
// for buying items from the store
for (int i = 0; i < storeItems.length; i++)
{
String buyValue = request.getParameter("Buy " + i);
if(buyValue != null)
{
if(gold < storeItems[i].getValue())
{
printStoreState(out);
out.println("<script> alert(\"You do not have enought gold.\") </script>");
return stateEnum.STORE;
}
gold -= storeItems[i].getValue();
updateGold(out);
// could also just move the last index to this index
try{
connectDB();
newItem(storeItems[i], out);
characterHasItem(storeItems[i], playerChar, out);
disconnectDB();
storeItems[i] = null;
getItems(out);
}
catch(Exception e)
{
error = "An error occured while trying to buy the item.";
}
break;
}
}
// for selling items player's inventory
for (int i = 0; i < playerChar.itemsHeld.length; i++){
String sellValue = request.getParameter("Sell " + i);
if(sellValue != null)
{
gold += Math.round((.6) * playerChar.itemsHeld[i].getValue());
// need to drop the item from the table
try{
connectDB();
deleteItem(playerChar.itemsHeld[i], out);
disconnectDB();
getItems(out);
}
catch(Exception e)
{
error = "failed to delete item from player's inventory.";
}
break;
}
}
printStoreState(out);
return stateEnum.STORE;
}
}
}
/****************************************************
* The initial state
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
private stateEnum battleState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.BATTLE)
{
//add a default aresChar incase the getNexrEnemy does not work
Integer Level = playerChar.getLevel();
Item[] itemsHeld = {generateWeapon(Level +1), generateArmor(Level+1)};
int aresHealth = constantHealthBase+(Level+1)*constantPtsPerLevel*constantHealthPerLevel;
int aresStrength = (Level+1)*constantPtsPerLevel*constantStrengthPerLevel;
int aresAgility = (Level+1)*constantPtsPerLevel*constantAgilityPerLevel;
int aresMagic = (Level+1)*constantPtsPerLevel*constantMagicPerLevel;
aresChar = new AresCharacter("Ares", "", Level, aresHealth, aresStrength, aresAgility, aresMagic, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0);
try {
getNextEnemy(playerChar.getLevel(), out);
} catch (SQLException ex) {
}
}
String startPage = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"header\" class=\"grid10\" align=\"center\">\n" +
" %s \n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <br />\n" +
" <p align=\"center\">\n" +
" </p>\n" +
" <div class=\"gridHalf\"> \n";
String statsTable =
" <h2 align=\"center\"> %s </h2>\n" +
" \n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <th> Health </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> %d </th>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String equippedTable1 =
" \n" +
" <h3 align=\"center\"> Equipped </h3>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> Weapon: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n";
String equippedTable2 =
" <tr>\n" +
" <th> Armor: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String betweenCharacters =
" </div>\n" +
" <div class=\"gridHalf\"> \n";
String afterTable =
" \n" +
" </div>\n" +
" <div class=\"grid10\">\n" +
" <div align=\"center\">\n"
+ " <form action=\"Tarsus\" method = \"post\">";
String attackButton =
" <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> <br /> \n" +
" <select name = \"itemSelected\"> \n";
String useButton =
" </select>" +
" <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n";
String lastPart =
" </form>" +
" <div class=\"grid1\"> </div> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
int aresDamage = 0, playerDamage = 0;
//The page clicked was in the battle state, so interpret the button pressed
if(startingState == stateEnum.BATTLE)
{
String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName;
if(valueAttack!=null)
value = valueAttack;
if(valueUse!=null)
{
value=valueUse;
itemName = request.getParameter("itemSelected");
}
if(valueOK!=null)
value=valueOK;
if(!value.equals("OK"))
{
actionEnum playerAction = playerChar.requestAction(request);
actionEnum aresAction = aresChar.requestAction(request);
if((playerAction == actionEnum.ATTACK)&&(aresAction == actionEnum.ATTACK))
{
//find which type of attack the player is using and calculate the damage
if(playerChar.weapon.getStrength()!=0)
{
aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100));
}
if(playerChar.weapon.getAgility()!=0)
{
aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100));
}
if(playerChar.weapon.getMagic()!=0)
{
aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100));
}
//find which type of attack the player is using and calculate the damage
if(aresChar.weapon.getStrength()!=0)
{
playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100));
}
if(aresChar.weapon.getMagic()!=0)
{
playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100));
}
if(aresChar.weapon.getAgility()!=0)
{
playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100));
}
}
//inflict the damage
playerChar.setHealth(playerChar.getHealth() - playerDamage);
aresChar.setHealth(aresChar.getHealth() - aresDamage);
}
//the player has been defeated
else if(playerChar.getHealth()<1)
{
//mark the character as dead in the database
updateCharacter(playerChar, true, out);
disconnectDB();
return stateEnum.PROFILE;
}
//the player defeated the enemy without dying
else if(aresChar.getHealth()<1)
return stateEnum.LEVEL_UP;
}
//print out most of the page
out.printf(startPage,accountName);
out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility());
out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility());
out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility());
out.printf(betweenCharacters);
out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility());
out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility());
out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility());
out.printf(afterTable);
out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage);
//the different ways the page can end
if((playerChar.getHealth()>0) && (aresChar.getHealth()>0))
{
out.printf(attackButton);
for(int i=0; i < playerChar.itemsHeld.length;i++)
{
//change first string, the value parameter, to itemId
if(playerChar.itemsHeld[i]!=null)
out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName());
}
out.printf(useButton);
}
else if(playerChar.getHealth()<1)
{
out.printf("The valiant hero has been killed. <br />\n");
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
else if(aresChar.getHealth()<1)
{
int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8));
gold+=newGold;
updateGold(out);
playerChar.setHealth(playerChar.getMaxHealth());
- out.printf("Congradulations you beat your enemy.\n You get %d gold.\n", newGold);
+ out.printf("CongratulationsCongradulations you beat your enemy.\n You get %d gold.\n", newGold);
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
out.printf(lastPart);
return stateEnum.BATTLE;
}
/****************************************************
* Create a registered user character
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum registeredCharacterCreationState(PrintWriter out, HttpServletRequest request) {
if((startingState != stateEnum.REGISTERED_CHARACTER_CREATION)|(error!=null))
{
//create new page
Integer level = 1;
printRegCharacterCreation(level, out);
error = null;
return stateEnum.REGISTERED_CHARACTER_CREATION;
}
else
{
//it was crashing on value == string constant on some cases, this is the only way to stop it
try{
stateEnum check = checkNameandLog(request);
if(check != stateEnum.REGISTERED_CHARACTER_CREATION)
return check;
}
catch(Exception e){
}
//if it makes it this far, a character needs to be made
charCreationParameters(out, request, false);
}
return stateEnum.DECISION;
}
/****************************************************
* Create an unregistered user character
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum unregisteredCharacterCreationState(PrintWriter out, HttpServletRequest request) {
if((startingState != stateEnum.UNREGISTERED_CHARACTER_CREATION)|(error!=null))
{
//create new page
Integer level = (int)(Math.random()*49+1);
printCharacterCreation(level, out);
error = null;
return stateEnum.UNREGISTERED_CHARACTER_CREATION;
}
else
{
//it was crashing on value == string constant on some cases, this is the only way to stop it
try
{
if(checkHome(request))
{
return stateEnum.INIT;
}
}
catch(Exception e)
{
return charCreationParameters(out, request, true);
}
//if it makes it this far create a new character
return charCreationParameters(out, request, true);
}
}
void printDecisionState(PrintWriter out)
{
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"POST\">\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input name=\"" + accountName + "\" value=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" /> \n" +
" <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">" + playerChar.getName() + "</h1>\n" +
" <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" +
" <p align=\"center\">\n" +
" <input name=\"To Battle!\" value=\"To Battle!\" type=\"submit\" class=\"profileButton\" />\n" +
" <input name=\"Store\" value=\"Store\" type=\"submit\" class=\"profileButton\" />\n" +
" <input name=\"Blacksmith\" value=\"Blacksmith\" type=\"submit\" class=\"profileButton\" />\n" +
" </p>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n");
printInventory(out);
out.println(" </form>\n" +
" </body>\n" +
"</html>");
}
/****************************************************
* Asking what the player wants to do next
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum decisionState(PrintWriter out, HttpServletRequest request) {
if (startingState != stateEnum.DECISION)
{
printDecisionState(out);
return stateEnum.DECISION;
}
else
{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
String value3 = request.getParameter("To Battle!");
String value4 = request.getParameter("Store");
String value5 = request.getParameter("Blacksmith");
if(value1 != null)
return stateEnum.PROFILE;
else if(value2 != null)
return stateEnum.LOGOUT;
else if(value3 != null)
return stateEnum.BATTLE;
else if(value4 != null)
return stateEnum.STORE;
else if(value5 != null)
return stateEnum.BLACKSMITH;
for (int i = 0; i < playerChar.itemsHeld.length; i++){
String tempValue = request.getParameter("Equip" + i);
if(tempValue != null)
{
String query = "";
if(playerChar.itemsHeld[i].getType() == 1)
{
query = "UPDATE Characters SET equippedWeapon='" + playerChar.itemsHeld[i].getItemId() + "' WHERE name='" + playerChar.getName() + "';";
}
else if(playerChar.itemsHeld[i].getType() == 2)
{
query = "UPDATE Characters SET equippedArmor='" + playerChar.itemsHeld[i].getItemId() + "' WHERE name='" + playerChar.getName() + "';";
}
else
{
//do nothing
}
connectDB();
sqlCommand(query, out);
disconnectDB();
getItems(out);
printDecisionState(out);
break;
}
}
return stateEnum.DECISION;
}
}
/****************************************************
* At the blacksmith and can upgrade items
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum blackSmithState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.BLACKSMITH)
{
printBlacksmithState(out);
return stateEnum.BLACKSMITH;
}
else
{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
if(value1 != null)
return stateEnum.DECISION;
else if(value2 != null)
return stateEnum.LOGOUT;
else
{
for (int i = 0; i < playerChar.itemsHeld.length; i++){
String tempValue = request.getParameter("Upgrade" + i);
if(tempValue != null)
{
if(gold < playerChar.itemsHeld[i].CONSTANT_upgradeGold)
{
printBlacksmithState(out);
out.println("<script> alert(\"You do not have enought gold.\") </script>");
return stateEnum.BLACKSMITH;
}
gold = gold - 50;
updateGold(out);
String query = "UPDATE Items SET upgradeCount=upgradeCount+1, ";
if(playerChar.itemsHeld[i].getType() == 1)
{
if(playerChar.itemsHeld[i].getStrength() > 0)
{
query = query + "strengthVal=strengthVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade;
}
if(playerChar.itemsHeld[i].getAgility() > 0)
{
query = query + "agilityVal=agilityVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade;
}
if(playerChar.itemsHeld[i].getMagic() > 0)
{
query = query + "magicVal=magicVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade;
}
}
else //playerChar.itemsHeld[i].getType() == 2
{
query = query + "strengthVal=strengthVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade +
"', agilityVal=agilityVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade +
"', magicVal=magicVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade;
}
query = query + "' WHERE itemId='" + playerChar.itemsHeld[i].getItemId() + "';";
connectDB();
sqlCommand(query, out);
disconnectDB();
getItems(out);
printBlacksmithState(out);
break;
}
}
return stateEnum.BLACKSMITH;
}
}
}
/****************************************************
* Registered user login state
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum loginState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.LOGIN){
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\"> \n" +
" <form method=\"post\" action=\"Tarsus\"> \n" +
" <input type=\"submit\" name=\"home\" value=\"TARSUS\" id=\"tarsusTitle\"> \n" +
" </form> </div>" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\"> Log In</h1>\n" +
" <form method=\"post\" action=\"Tarsus\"> \n" +
" <p align=\"center\"> \n" +
" Username: <input name=\"username\" type=\"text\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" Password: <input name=\"password\" type=\"password\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" <input class=\"signUpButton\" value=\"Log In\" type=\"submit\"/>\n" +
" </p>\n" +
" </form>\n" +
" </div>\n" +
"</html>");
}else{
String value1 = request.getParameter("home");
String value = "";
if(value1 != null)
value = value1;
if(value.equals("TARSUS"))
return stateEnum.INIT;
String username = request.getParameter("username");
int password = request.getParameter("password").hashCode();
if(!isValidString(username)){
out.println("Error");
return stateEnum.LOGIN;
}
String search = "SELECT * FROM Login WHERE username='" + username +
"' AND password= MD5('" + password+ "');";
connectDB();
ResultSet result = sqlQuery(search, out);
try{
if(result.isBeforeFirst()){
result.next();
accountName = username;
gold = result.getInt("gold");
return stateEnum.PROFILE;
}else{
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\"> \n" +
" <a href=\"index.jsp\" id=\"tarsusTitle\"> TARSUS </a> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\"> Log In</h1>\n" +
" <h3>Invalid Login </h3> \n " +
" <form method=\"post\" action=\"Tarsus\"> \n " +
" <p align=\"center\"> \n" +
" Username: <input name=\"username\" type=\"text\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" Password: <input name=\"password\" type=\"password\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" <input class=\"signUpButton\" value=\"Log In\" type=\"submit\"/>\n" +
" </p>\n" +
" </form>\n" +
" </div>\n" +
"</html>");
return stateEnum.LOGIN;
}
}catch(Exception ex){
out.println("Login SQL Error: " + ex);
}
}
return stateEnum.LOGIN;
}
/****************************************************
* Registered user creation state
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
stateEnum accountCreation(PrintWriter out, HttpServletRequest request) throws SQLException {
String accountPageBegin = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\"> \n" +
" <form method=\"post\" action=\"Tarsus\"> \n" +
" <input type=\"submit\" name=\"home\" value=\"TARSUS\" id=\"tarsusTitle\"> \n" +
" <input type=\"submit\" name=\"login\" value=\"Log In\" class=\"button\" href=\"login.html\"> \n" +
" </form> </div>" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\"> Sign Up Below</h1>\n";
String accountPageEnd =
" <form method=\"post\" action=\"Tarsus\"> \n" +
" <p align=\"center\"> \n" +
" Username: <input name=\"username\" type=\"text\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" Password: <input name=\"password\" type=\"password\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" Confirm Password: <input name=\"confirmpassword\" type=\"password\" /> \n" +
" </p>\n" +
" <p align=\"center\"> \n" +
" <input class=\"signUpButton\" value=\"Sign Up\" type=\"submit\"/> \n" +
" </p>\n" +
" </form>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" \n" +
"</html>";
if(startingState != stateEnum.ACCOUNT_CREATION)
{
out.println(accountPageBegin + accountPageEnd);
return stateEnum.ACCOUNT_CREATION;
}
else{
String value1 = request.getParameter("home");
String value2 = request.getParameter("login");
String value = "";
if(value1 != null)
value = value1;
if(value2!=null)
value = value2;
if(value.equals("Log In"))
return stateEnum.LOGIN;
if(value.equals("TARSUS"))
return stateEnum.INIT;
String username = request.getParameter("username");
String findUsername = "SELECT username FROM Login "
+ "WHERE username = \"" + username + "\";";
Boolean alreadyExists = false;
try{
connectDB();
ResultSet result = sqlQuery(findUsername, out);
if(result.isBeforeFirst()){
alreadyExists= true;
}
}catch(Exception ex){
out.println("username check failure"); //Test Check
out.println(ex);
alreadyExists=true;
}
DBUtilities.closeStatement(stat);
disconnectDB();
// Check to see if the username is valid
if(!isValidString(username) || alreadyExists)
{
out.println(accountPageBegin +
"<h3 id=\"title\" class=\"centered\"> Invalid Username "
+ "</h3 \n" + accountPageEnd);
return stateEnum.ACCOUNT_CREATION;
}
int password = request.getParameter("password").hashCode();
int confirmPassword = request.getParameter("confirmpassword").hashCode();
if(password != confirmPassword){
out.println(accountPageBegin +
"<h3 id=\"title\" class=\"centered\"> The Passwords Do "
+ "Not Match </h3 \n" + accountPageEnd);
return stateEnum.ACCOUNT_CREATION;
}
String command = "INSERT INTO Login VALUES ('" + username + "', MD5('"
+ password +"'), gold=0);";
try{
connectDB();
if(sqlCommand(command, out))
{
DBUtilities.closeStatement(stat);
disconnectDB();
return stateEnum.LOGIN;
}
else{
out.println(accountPageBegin +"<h1> ERROR! </h1>"+ accountPageEnd);
return stateEnum.ACCOUNT_CREATION;
}
}catch(Exception ex)
{
out.println("SQL Command Error:");
out.println(ex);
return stateEnum.ACCOUNT_CREATION;}
}
}
stateEnum profileState(PrintWriter out, HttpServletRequest request) throws SQLException {
if(startingState != stateEnum.PROFILE)
{
printProfileState(out);
}
else
{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
String value3 = request.getParameter("Create Character");
String value4 = request.getParameter("Load Character");
String value5 = request.getParameter("Look at Past Characters");
String value6 = request.getParameter("Look at All Characters");
String value = "";
if(value1 != null)
value = value1;
if(value2 != null)
value = value2;
if(value3 != null)
value = value3;
if(value4 != null)
value = value4;
if(value5 != null)
value = value5;
if(value6 != null)
value = value6;
if(value.equals(accountName))
printProfileState(out);
if(value.equals("Log Out"))
return stateEnum.LOGOUT;
if(value.equals("Create Character"))
return stateEnum.REGISTERED_CHARACTER_CREATION;
if(value.equals("Load Character"))
{
String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;";
connectDB();
ResultSet result = sqlQuery(search1, out);
if(result.isBeforeFirst())
{
result.next();
String name = result.getString("name");
String bio = result.getString("bio");
int level = result.getInt("level");
int health = result.getInt("health");
int strength = result.getInt("strength");
int agility = result.getInt("agility");
int magic = result.getInt("magic");
int timesAttacked = result.getInt("timesAttacked");
int timesSwitchedToStrength = result.getInt("timesSwitchedToStrength");
int timesSwitchedToAgility = result.getInt("timesSwitchedToAgility");
int timesSwitchedToMagic = result.getInt("timesSwitchedToMagic");
int equipWeaponId = result.getInt("equippedWeapon");
int equipArmorId = result.getInt("equippedArmor");
disconnectDB();
//getting the length for itemsHeld
connectDB();
String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';";
result = sqlQuery(search2, out);
result.next();
int rows = result.getInt("rows");
disconnectDB();
Item[] itemsHeld = new Item[rows];
Item weapon = null;
Item armor = null;
String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';";
connectDB();
result = sqlQuery(search3, out);
//temp varible
int i = 0;
while (result.next())
{
String iName = result.getString("name");
int itemId = result.getInt("itemId");
int type = result.getInt("type");
int upgradeCount = result.getInt("upgradeCount");
int strengthVal= result.getInt("strengthVal");
int agilityVal = result.getInt("agilityVal");
int magicVal = result.getInt("magicVal");
Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0);
itemsHeld[i] = item;
if (equipWeaponId == itemId)
{
weapon = item;
}
if (equipArmorId == itemId)
{
armor = item;
}
i++;
}
disconnectDB();
playerChar = new PlayerCharacter(name, bio, level, health, strength, agility, magic, itemsHeld, weapon, armor, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic);
return stateEnum.DECISION;
}
else
{
out.println("No Valid Character");
printProfileStateNewChar(out);
return stateEnum.PROFILE;
}
}
if(value.equals("Look at Past Characters"))
return stateEnum.PAST_CHARACTERS;
if(value.equals("Look at All Characters"))
return stateEnum.ALL_CHARACTERS;
}
return stateEnum.PROFILE;
}
stateEnum allCharactersState(PrintWriter out, HttpServletRequest request)
{
if(startingState != stateEnum.ALL_CHARACTERS)
{
String startPart = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> ALL Characters </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"get\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input name=\"" + accountName + "\" value=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" /> \n" +
" <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">All Characters</h1>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <th> Name </th>\n" +
" <th> Level </th>\n" +
" <th> Status </th>\n" +
" <th> Account </th>\n" +
" <th> Bio </th>\n" +
" </tr>\n";
String lastPart =
" </table>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>" +
" </body>\n" +
" \n" +
"</html>";
out.println(startPart);
ResultSet result;
int rows = 0;
try
{
//getting the amount of dead characters
String search1 = "SELECT COUNT(name) AS rows FROM Characters;";
connectDB();
result = sqlQuery(search1, out);
result.next();
rows = result.getInt("rows");
disconnectDB();
}
catch(Exception ex)
{
out.println("Error in getting rows: " + ex);
}
String search2 = "SELECT * FROM Characters;";
connectDB();
try
{
result = sqlQuery(search2, out);
while (result.next())
{
out.println("<td>");
out.println(result.getString("name"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("level"));
out.println("</td>");
out.println("<td>");
if(result.getInt("isDead") == 0)
out.println("Alive");
else
out.println("Dead");
out.println("</td>");
out.println("<td>");
out.println(result.getString("creator"));
out.println("</td>");
out.println("<td>");
if(result.getString("bio") != "Auto Added")
out.println("No Description Given");
else
out.println(result.getString("bio"));
out.println("</td>");
out.println("</tr>\n");
}
}
catch(Exception ex)
{
out.println("Error grabbing characters: " + ex);
}
disconnectDB();
out.println(lastPart);
return stateEnum.ALL_CHARACTERS;
}
else
{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
String value = "";
if(value1 != null)
value = value1;
if(value2 != null)
value = value2;
if(value.equals(accountName))
return stateEnum.PROFILE;
if(value.equals("Log Out"))
return stateEnum.LOGOUT;
else
return stateEnum.ALL_CHARACTERS;
}
//return stateEnum.PROFILE;
}
stateEnum pastCharactersState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.PAST_CHARACTERS)
{
String startPart = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"get\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input name=\"" + accountName + "\" value=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" /> \n" +
" <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Past Characters</h1>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <th> Name </th>\n" +
" <th> Level </th>\n" +
" <th> Health </th>\n" +
" <th> Strength </th>\n" +
" <th> Agility </th>\n" +
" <th> Magic </th>\n" +
" <th> Bio </th>\n" +
" </tr>\n";
String lastPart = " </tr>\n" +
" </table>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>" +
" </body>\n" +
" \n" +
"</html>";
out.println(startPart);
ResultSet result;
int rows = 0;
try
{
//getting the amount of dead characters
String search1 = "SELECT COUNT(name) AS rows FROM Characters WHERE creator='" + accountName + "' AND isDead=1;";
connectDB();
result = sqlQuery(search1, out);
result.next();
rows = result.getInt("rows");
disconnectDB();
}
catch(Exception ex)
{
out.println("Error in getting rows: " + ex);
}
boolean noDead;
if(rows > 0)
{
noDead = false;
}
else
{
noDead = true;
}
String search2 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=1;";
connectDB();
try
{
result = sqlQuery(search2, out);
if(noDead)
{
out.println("<tr>");
out.println("<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n");
out.println("</tr>");
}
else //there are one or more dead characters
{
while (result.next())
{
out.println("<td>");
out.println(result.getString("name"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("level"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("health"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("strength"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("agility"));
out.println("</td>");
out.println("<td>");
out.println(result.getInt("magic"));
out.println("</td>");
out.println("<td>");
out.println(result.getString("bio"));
out.println("</td>");
out.println("</tr>\n");
}
}
}
catch(Exception ex)
{
out.println("Error grabbing dead characters: " + ex);
}
disconnectDB();
out.println(lastPart);
return stateEnum.PAST_CHARACTERS;
}
else
{
String value1 = request.getParameter(accountName);
String value2 = request.getParameter("Log Out");
String value = "";
if(value1 != null)
value = value1;
if(value2 != null)
value = value2;
if(value.equals(accountName))
return stateEnum.PROFILE;
if(value.equals("Log Out"))
return stateEnum.LOGOUT;
}
return stateEnum.PROFILE;
}
stateEnum LogoutState(PrintWriter out, HttpServletRequest request) {
playerChar = null;
aresChar = null;
accountName = "Unregistered User";
gold = 0;
error = null;
//accountName = null;
return stateEnum.INIT;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/****************************************************
* Checks the validity of a String for the database
* @param string the string to check for validity
* @return the validity
***************************************************/
Boolean isValidString(String string)
{
Boolean toBeReturned = true;
if(string.contains("drop"))
toBeReturned = false;
if(string.contains("delete"))
toBeReturned = false;
if(string.contains(";"))
toBeReturned = false;
if(string.contains("'"))
toBeReturned = false;
return toBeReturned;
}
String maxValueScript(int value)
{
return ("<script> var maxValue=" + Integer.toString(value) +";</script>");
}
double getQuality(int level)
{
double ratio = ((double)level) / ((double)level + 5.0);
double quality = Math.random() * ratio;
return quality;
}
void printBlacksmithState(PrintWriter out)
{
String startPart = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input value=\"" + accountName + "\" name=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" />\n" +
" <input class=\"button\" value=\"Log Out\" name=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Blacksmith</h1>\n" +
" <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Upgrade Cost </th>\n" +
" <th> Strength </th>\n" +
" <th> Agility </th>\n" +
" <th> Magic </th>\n" +
" <th> Type </th>\n" +
" <th> Times Upgraded </th>\n" +
" </tr>\n";
String endPart = "</table>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>" +
" </body>\n" +
" \n" +
"</html>";
out.println(startPart);
boolean noItems;
if(playerChar.itemsHeld.length > 0)
{
noItems = false;
}
else
{
noItems = true;
}
if(noItems)
{
out.println("<tr>");
out.println("<td> </td>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n" +
"<th></th>\n");
out.println("</tr>");
}
else //there are one or more items
{
for (int i = 0; i < playerChar.itemsHeld.length; i++){
if(playerChar.itemsHeld[i].getUpgradeCount() < 3)
{
out.println("<tr>\n");
out.println("<td> <input value=\"Upgrade\" name=\"Upgrade" + i + "\" type=\"submit\" class=\"tableButton\" /> </td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getName());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].CONSTANT_upgradeGold);
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getStrength());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getAgility());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getMagic());
out.println("</td>");
out.println("<td>");
out.println(item_type_string[playerChar.itemsHeld[i].getType()]);
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getUpgradeCount());
out.println("</td>");
out.println("</tr>\n");
}
}
}
out.println(endPart);
}
void printProfileState(PrintWriter out)
{
try{
String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;";
connectDB();
ResultSet result = sqlQuery(search1, out);
if(result.isBeforeFirst())
{
printProfileStateLoadChar(out);
}
else{
printProfileStateNewChar(out);
}
} catch(Exception ex){
out.println(ex);
}
}
void printProfileStateNewChar(PrintWriter out)
{
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" type=\"submit\" /> \n" +
" <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid2\"> </div>\n" +
" <div class=\"grid6 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">TARSUS</h1> <br />\n" +
" <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" +
" <div align=\"center\"> \n" +
" <input class=\"profileButton\" name=\"Create Character\" value=\"Create Character\" type=\"submit\" />\n" +
" <input class=\"profileButton\" name=\"Look at Past Characters\" value=\"Look at Past Characters\" type=\"submit\" /> \n" +
" <input class=\"profileButton\" name=\"Look at All Characters\" value=\"Look at All Characters\" type=\"submit\" /> \n" +
" </div>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>" +
" </body>\n" +
" \n" +
"</html>");
}
void printProfileStateLoadChar(PrintWriter out)
{
out.println("<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <input name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" type=\"submit\" /> \n" +
" <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" +
" <div class=\"grid2\"> </div>\n" +
" <div class=\"grid6 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">TARSUS</h1> <br />\n" +
" <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" +
" <div align=\"center\"> \n" +
" <input class=\"profileButton\" name=\"Load Character\" value=\"Load Character\" type=\"submit\" /> \n" +
" <input class=\"profileButton\" name=\"Look at Past Characters\" value=\"Look at Past Characters\" type=\"submit\" /> \n" +
" <input class=\"profileButton\" name=\"Look at All Characters\" value=\"Look at All Characters\" type=\"submit\" /> \n" +
" </div>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </form>" +
" </body>\n" +
" \n" +
"</html>");
}
public void printStoreState(PrintWriter out)
{
//String item_type_string[] = {"Error", "Weapon", "Armor", "Item"};
String startPart = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <input value=\"" + accountName + "\" name=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" />\n" +
" <input class=\"button\" type=\"submit\" value=\"Log Out\" name=\"Log Out\" /> </div>\n" + "</form>" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Store Inventory</h1>\n" +
" <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Agility </th>\n" +
" <th> Magic </th>\n" +
" <th> Heal </th>\n" +
" <th> Type </th>\n" +
" <th> Price </th>\n" +
" </tr>\n" +
" <tr>";
String sellPart = " </table>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid10\">" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Your Items</h1>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Agility </th>\n" +
" <th> Magic </th>\n" +
" <th> Heal </th>\n" +
" <th> Type </th>\n" +
" <th> Sell Price </th>\n" +
" </tr>\n" +
" ";
String buttonPart = " </table>\n" +
" </div>\n" +
//" <div class=\"grid1\"> </div> </div>\n" +
// " <div class=\"grid10\" align=\"center\">\n" +
// " <input id=\"Form\" type =\"submit\" value=\"This button does not do anything\" class=frontPageButton /> \n" +
// " </div>\n" +
" </form>\n";
String endPart =
/*"</table>\n" +"</div>\n" +*/
" </body>\n" +
" \n" +
"</html>";
String script = "<script> function getFormValues() {" +
"for(var i = 0; i < 20; i++){" +
" var item = document.getElementById('i');" +
" alert(item.getAttribute('name'));" +
"} return false;} </script>";
out.println(startPart);
out.println("<form name=\"buyItems\" action=\"Tarsus\" onsubmit=\"return getFormValues()\" method=\"post\">\n");
for (int i = 0; i < storeItems.length; i++){
out.println("<tr>");
if(storeItems[i] == null)
{
out.println("<td> </td>");
out.println("<td> Item sold out</td>");
out.println("<td> n/a </td>");
out.println("<td> n/a </td>");
out.println("<td> n/a </td>");
out.println("<td> n/a </td>");
out.println("<td> n/a </td>");
out.println("<td> n/a </td>");
out.println("</tr>");
}
else{
//out.println(storeItems[i]);
out.println("<tr>");
out.println("<td> <input type=\"submit\" value=\"Buy" + "\" name=\"Buy " + i + "\" class=\"tableButton\"> </td>");
out.println("<td>");
out.println(storeItems[i].getName());
out.println("</td>");
out.println("<td>");
out.println(storeItems[i].getStrength());
out.println("</td>");
out.println("<td>");
out.println(storeItems[i].getAgility());
out.println("</td>");
out.println("<td>");
out.println(storeItems[i].getMagic());
out.println("</td>");
out.println("<td>");
out.println(storeItems[i].getHeal());
out.println("</td>");
out.println("<td>");
out.println(item_type_string[storeItems[i].getType()]);
out.println("</td>");
out.println("<td id =\"" + i + "\" ");
out.println("value=" + storeItems[i].getValue() + " >");
out.println(storeItems[i].getValue());
out.println("</td>");
out.println("</tr>");
}
}
out.println(sellPart);
//out.println("player items held length: " + playerChar.itemsHeld.length);
for (int i = 0; i < playerChar.itemsHeld.length; i++){
if(playerChar.itemsHeld[i] == null)
{
continue;
}
out.println("<tr>");
//out.println(" loop level: " + i);
out.println("<td>");
if((playerChar.itemsHeld[i] != playerChar.weapon) && (playerChar.itemsHeld[i] != playerChar.armor))
{
out.println("<input type=\"submit\" value=\"Sell" + "\" name=\"Sell " + i + "\" class=\"tableButton\">");
}
else
{
out.println("Equiped Item");
}
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getName());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getStrength());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getAgility());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getMagic());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getHeal());
out.println("</td>");
out.println("<td>");
out.println(item_type_string[playerChar.itemsHeld[i].getType()]);
out.println("</td>");
out.println("<td>");
out.println((int)(0.60 * (double)(playerChar.itemsHeld[i].getValue())));
out.println("</td>");
out.println("</tr>");
}
out.println(buttonPart);
out.println(endPart);
out.println(script);
}
/****************************************************
* The state for handling a level up
* @param out the print writer
* @param request the servlet request
* @return the next state
***************************************************/
private stateEnum levelUpState(PrintWriter out, HttpServletRequest request)
{
if(startingState != stateEnum.LEVEL_UP)
{
String page = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <script>\n" +
" function validateForm()\n" +
" {\n" +
" \n" +
" var maxValue = 5 \n" +
" var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" +
" var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" +
" var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" +
" var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" +
" var total = strength + agility + magic + health;\n" +
" if(total > maxValue)\n" +
" {\n" +
" alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" +
" return false;\n" +
" }\n" +
" \n" +
" }\n" +
" </script>" +
" <body>\n" +
"<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
"<input type=\"Submit\" name=\"Home\" value=\"Home\" id=\"tarsusTitle\" />" +
" <div class=\"grid1\"> </div></div>\n" +
" <div class=\"grid1\"> </div>" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" +
" \n" +
" <div class=\"grid2\"> </div>\n" +
" <div class=\"grid6\" align=\"center\">\n" +
" <p> Experience Points to Allocate: 5\n" +
" </p>\n" +
" <p> \n" +
" Strength is currently %d add: <input type=\"number\" name=\"strength\"min=\"0\" max=\"5\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Agility is currently %d add: <input type=\"number\" name=\"agility\"min=\"0\" max=\"5\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Magic is currently %d add: <input type=\"number\" name=\"magic\" min=\"0\" max=\"5\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Health is currently %d add: <input type=\"number\" name=\"health\" min=\"0\" max=\"5\" value=\"0\"/>\n" +
" </p> \n" +
" </div>\n"+
" <div class=\"grid10\" align=\"center\">\n" +
" <input type =\"submit\" value=\"update level\" class=frontPageButton /> \n" +
" </div>\n" +
" </form>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
//find out the number of points put into different skills
int Strength = playerChar.getStrength()/constantStrengthPerLevel;
int Agility = playerChar.getAgility()/constantAgilityPerLevel;
int Magic = playerChar.getMagic()/constantMagicPerLevel;
int Health = (playerChar.getMaxHealth()-constantHealthBase)/constantHealthPerLevel;
out.printf(page, Strength,Agility, Magic, Health);
return stateEnum.LEVEL_UP;
}
else
{
//get the parameters
int health = Integer.parseInt(request.getParameter("health"));
int strength = Integer.parseInt(request.getParameter("strength"));
int agility = Integer.parseInt(request.getParameter("agility"));
int magic = Integer.parseInt(request.getParameter("magic"));
//calculated the new values
playerChar.setMaxHealth(playerChar.getMaxHealth()+health*constantHealthPerLevel);
playerChar.setHealth(playerChar.getMaxHealth());
playerChar.setStrength(playerChar.getStrength()+strength*constantStrengthPerLevel);
playerChar.setAgility(playerChar.getAgility()+agility*constantAgilityPerLevel);
playerChar.setMagic(playerChar.getMagic()+magic*constantMagicPerLevel);
playerChar.setLevel(playerChar.getLevel()+1);
//update database
updateCharacter(playerChar, false, out);
disconnectDB();
return stateEnum.DECISION;
}
}
/****************************************************
* Prints the page for unregistered character creation
* @param level the level of the character to create
* @param out the PrintWriter for the page
***************************************************/
private void printCharacterCreation(Integer level, PrintWriter out) {
String StartPage = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <script>\n" +
" function validateForm()\n" +
" {\n" +
" \n" +
" var maxValue = ";
String secondPart = "; \n" +
" var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" +
" var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" +
" var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" +
" var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" +
" var total = strength + agility + magic + health;\n" +
" alert(\"Total Experience points used: \" + total);\n" +
" if(total > maxValue)\n" +
" {\n" +
" alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" +
" return false;\n" +
" }\n" +
" \n" +
" }\n" +
" </script>" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
"<input type=\"Submit\" name=\"Home\" value=\"Home\" id=\"tarsusTitle\" />" +
" <div class=\"grid1\"> </div></div>\n" +
" <div class=\"grid1\"> </div>"+
" <div class=\"grid8 centered\">\n" +
"</form>" +
"<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" +
" <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" +
" \n" +
" <div class=\"grid2\"> </div>\n" +
" <input type = \"hidden\" name = \"level\" value=\"";
String thirdPart = "\"/>\n"+
" <div class=\"grid6\" align=\"center\">\n" +
" <h3> Level ";
String fourthPart = " </h3>\n" +
" <p> Experience Points to Allocate: ";
String fifthPart = "\n" +
" </p>\n" +
" <p> \n" +
" Name: <input type=\"text\" name=\"name\"/>\n" +
" </p>\n" +
" <p> \n" +
" Strength: <input type=\"number\" name=\"strength\"min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Agility: <input type=\"number\" name=\"agility\"min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Magic: <input type=\"number\" name=\"magic\" min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Health: <input type=\"number\" name=\"health\" min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p>\n" +
" Biography:<textarea name=\"bio\" cols=\"35\" rows=\"3\" maxlength=\"300\"> </textarea> <br /> <a id=\"bioLimitID\"> (Max of 300 Chars)</a>\n" +
" </p>\n";
String lastPart =
" </div>\n"+
" <div class=\"grid10\" align=\"center\">\n" +
" <input type =\"submit\" value=\"Create a Character\" class=frontPageButton /> \n" +
" </div>\n" +
" </form>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
int numItemChoices = 5;
Item tempItem;
String submitValue;
out.printf(StartPage);
out.println(((Integer)(level*constantPtsPerLevel)).toString());
out.printf(secondPart);
out.printf(level.toString());
out.printf(thirdPart);
out.printf(level.toString());
out.printf(fourthPart);
out.printf(((Integer)(level*constantPtsPerLevel)).toString());
out.printf(fifthPart);
out.printf("<input type=\"hidden\" name=\"level\" value=\"%d\" />\n",level);
//print out the weapon choices
out.println("<table><tr><h2>Weapons</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>");
for(int i=0; i<numItemChoices; i++)
{
tempItem = generateWeapon(level);
submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString();
//the first choice is automatically checked
if(i==0)
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
else
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
}
out.println("</table>");
//print out the armor choices
out.println("<table><tr><h2>Armor</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>");
for(int i=0; i<numItemChoices; i++)
{
tempItem = generateArmor(level);
submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString();
//the first one is automatically checked
if(i==0)
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
else
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
}
out.println("</table>");
out.println(lastPart);
if(error!=null)
out.printf("<script>alert(\"%s\");</script>",error);
error = null;
}
/****************************************************
* Prints the page for registered character creation
* @param level the level of the character to create
* @param out the PrintWriter for the page
***************************************************/
private void printRegCharacterCreation(Integer level, PrintWriter out) {
String StartPage = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <script>\n" +
" function validateForm()\n" +
" {\n" +
" \n" +
" var maxValue = ";
String secondPart = "; \n" +
" var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" +
" var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" +
" var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" +
" var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" +
" var total = strength + agility + magic + health;\n" +
" alert(\"Total Experience points used: \" + total);\n" +
" if(total > maxValue)\n" +
" {\n" +
" alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" +
" return false;\n" +
" }\n" +
" \n" +
" }\n" +
" </script>" +
" <body>\n" +
" <form action=\"Tarsus\" method=\"post\">" +
" <div id=\"header\" class=\"grid10\" align=\"right\">\n" +
"<input type=\"Submit\" name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" />" +
"<input class=\"button\" type=\"Submit\" name=\"Log Out\" value=\"Log Out\" />" +
" <div class=\"grid1\"> </div></div>\n" +
" <div class=\"grid1\"> </div>"+
" <div class=\"grid8 centered\">\n" +
"</form>" +
"<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" +
" <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" +
" \n" +
" <div class=\"grid2\"> </div>\n" +
" <input type = \"hidden\" name = \"level\" value=\"";
String thirdPart = "\"/>\n"+
" <div class=\"grid6\" align=\"center\">\n" +
" <h3> Level ";
String fourthPart = " </h3>\n" +
" <p> Experience Points to Allocate: ";
String fifthPart = "\n" +
" </p>\n" +
" <p> \n" +
" Name: <input type=\"text\" name=\"name\"/>\n" +
" </p>\n" +
" <p> \n" +
" Strength: <input type=\"number\" name=\"strength\"min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Agility: <input type=\"number\" name=\"agility\"min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Magic: <input type=\"number\" name=\"magic\" min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p> \n" +
" Health: <input type=\"number\" name=\"health\" min=\"0\" max=\"100\" value=\"0\"/>\n" +
" </p> \n" +
" <p>\n" +
" Biography:<textarea name=\"bio\" cols=\"35\" rows=\"3\" maxlength=\"300\"> </textarea> <br /> <a id=\"bioLimitID\"> (Max of 300 Chars)</a>\n" +
" </p>\n";
String lastPart =
" </div>\n"+
" <div class=\"grid10\" align=\"center\">\n" +
" <input type =\"submit\" value=\"Create a Character\" class=frontPageButton /> \n" +
" </div>\n" +
" </form>\n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
int numItemChoices = 5;
Item tempItem;
String submitValue;
out.printf(StartPage);
out.println(((Integer)(level*constantPtsPerLevel)).toString());
out.printf(secondPart);
out.printf(level.toString());
out.printf(thirdPart);
out.printf(level.toString());
out.printf(fourthPart);
out.printf(((Integer)(level*constantPtsPerLevel)).toString());
out.printf(fifthPart);
out.printf("<input type=\"hidden\" name=\"level\" value=\"%d\" />\n",level);
//print the weapon choices
out.println("<table><tr><h2>Weapons</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>");
for(int i=0; i<numItemChoices; i++)
{
tempItem = generateWeapon(level);
submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString();
//the first choice is the defualt selected option
if(i==0)
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
else
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
}
out.println("</table>");
//print fout the armor choices
out.println("<table><tr><h2>Armor</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>");
for(int i=0; i<numItemChoices; i++)
{
tempItem = generateArmor(level);
submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString();
//the first one is selected by default
if(i==0)
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
else
out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue);
}
out.println("</table>");
out.println(lastPart);
if(error!=null)
out.printf("<script>alert(\"%s\");</script>",error);
error = null;
}
/****************************************************
* Checks the parameters for the home button being pressed
* @param request the servlet request
* @return whether or not it was pressed
***************************************************/
private boolean checkHome(HttpServletRequest request)
{
String value = request.getParameter("Home");
return value.equals("Home");
}
/****************************************************
* Checks for the name or loggout being pressed
* @param request the servlet request
* @return the next state, possibly the current state
***************************************************/
stateEnum checkNameandLog(HttpServletRequest request)
{
String name = request.getParameter(accountName), logOut = request.getParameter("Log Out");
try{
if(name!=null)
return stateEnum.PROFILE;
}
catch(Exception e){}
try{
if(logOut != null)
return stateEnum.LOGOUT;
}
catch(Exception e){}
return stateEnum.REGISTERED_CHARACTER_CREATION;
}
private void printInventory(PrintWriter out)
{
String startPart =
" <div class=\"grid1 centered\"> </div>\n" +
"<div class=\"grid10\"> \n <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <h1 id=\"title\" class=\"centered\">Your Inventory</h1>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Agility </th>\n" +
" <th> Magic </th>\n" +
" <th> Heal </th>\n" +
" <th> Type </th>\n" +
" <th> Upgrade Count </th>\n" +
" </tr>\n" +
" ";
String endPart = "</table> </div> </div>";
out.println(startPart);
for (int i = 0; i < playerChar.itemsHeld.length; i++){
if(playerChar.itemsHeld[i] == null)
{
continue;
}
out.println("<tr>");
//out.println(" loop level: " + i);
out.println("<td>");
if(playerChar.itemsHeld[i] == playerChar.armor)
{
out.println("<b>Equiped Armor</b>");
}
else if(playerChar.itemsHeld[i] == playerChar.weapon)
{
out.println("<b>Equiped Weapon</b>");
}
else
{
// Will Give the option to equip other itmes here
if((playerChar.itemsHeld[i].getType() == 1) || (playerChar.itemsHeld[i].getType() == 2))
{
out.println("<input value=\"Equip\" name=\"Equip" + i + "\" type=\"submit\" class=\"tableButton\" />");
}
else
{
out.println("Cannot Equip");
}
}
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getName());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getStrength());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getAgility());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getMagic());
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getHeal());
out.println("</td>");
out.println("<td>");
out.println(item_type_string[playerChar.itemsHeld[i].getType()]);
out.println("</td>");
out.println("<td>");
out.println(playerChar.itemsHeld[i].getUpgradeCount());
out.println("</td>");
out.println("</tr>");
}
out.println(endPart);
}
/****************************************************
* Interprets the character creation parameters
* @param out the print writer
* @param request the servlet request
* @param isUnReg whether or not the user is signed in
* @return the next state
***************************************************/
private stateEnum charCreationParameters(PrintWriter out, HttpServletRequest request, Boolean isUnReg) {
//load the parameters
String name = (String) request.getParameter("name");
String bio = request.getParameter("bio");
int level = Integer.parseInt(request.getParameter("level"));
int health = (Integer.parseInt(request.getParameter("health"))*constantHealthPerLevel + constantHealthBase);
int strength = (Integer.parseInt(request.getParameter("strength"))*constantStrengthPerLevel);
int agility = (Integer.parseInt(request.getParameter("agility"))*constantAgilityPerLevel);
int magic = (Integer.parseInt(request.getParameter("magic"))*constantMagicPerLevel);
//load the weapon and armor choices
String weap = request.getParameter("weapon");
Item weap2 = new Item(weap);
String armor = request.getParameter("armor");
Item armor2 = new Item(armor);
Item[] items = {weap2, armor2};
//check to see if the name is already in use
try{
String findCharName = "SELECT name FROM Characters "
+ "WHERE name = \"" + name + "\";";
Boolean alreadyExists = false;
connectDB();
ResultSet result = sqlQuery(findCharName, out);
if(result.isBeforeFirst()){
alreadyExists= true;
}
//make the character
if(isValidString(name) & isValidString(bio) & !alreadyExists)
{
newItem(items[0], out);
newItem(items[1], out);
PlayerCharacter chrct = new PlayerCharacter(name,bio, level, health, strength, agility, magic, items,items[0],items[1],0,0,0,0);
newCharacter(chrct,isUnReg, out);
characterHasItem(items[0], chrct, out);
characterHasItem(items[1], chrct, out);
disconnectDB();
if(isUnReg)
return stateEnum.INIT;
playerChar = chrct;
return stateEnum.DECISION;
}
else
{
//report any errors
error = "The character name or bio is invalid or there was a database error";
if(alreadyExists)
error = "That name is already in use";
if(isUnReg)
return stateEnum.UNREGISTERED_CHARACTER_CREATION;
return stateEnum.REGISTERED_CHARACTER_CREATION;
}
}
catch(Exception e)
{
error = "The character name or bio is invalid or there was a database error";
if(isUnReg)
return stateEnum.UNREGISTERED_CHARACTER_CREATION;
return stateEnum.REGISTERED_CHARACTER_CREATION;
}
}
void getItems(PrintWriter out)
{
playerChar.weapon = null;
playerChar.armor = null;
playerChar.itemsHeld = null;
try
{
String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;";
connectDB();
ResultSet result = sqlQuery(search1, out);
if(result.isBeforeFirst())
{
result.next();
int equipWeaponId = result.getInt("equippedWeapon");
int equipArmorId = result.getInt("equippedArmor");
disconnectDB();
//getting the length for itemsHeld
connectDB();
String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + playerChar.getName() + "';";
result = sqlQuery(search2, out);
result.next();
int rows = result.getInt("rows");
disconnectDB();
playerChar.itemsHeld = new Item[rows];
String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + playerChar.getName() + "';";
connectDB();
result = sqlQuery(search3, out);
//temp varible
int i = 0;
while (result.next())
{
String iName = result.getString("name");
int itemId = result.getInt("itemId");
int type = result.getInt("type");
int upgradeCount = result.getInt("upgradeCount");
int strengthVal= result.getInt("strengthVal");
int agilityVal = result.getInt("agilityVal");
int magicVal = result.getInt("magicVal");
Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0);
playerChar.itemsHeld[i] = item;
if (equipWeaponId == itemId)
{
playerChar.weapon = item;
}
if (equipArmorId == itemId)
{
playerChar.armor = item;
}
i++;
}
disconnectDB();
}
}
catch(Exception ex)
{
out.println("Error: " + ex);
}
}
void updateGold(PrintWriter out)
{
connectDB();
String query = "UPDATE Login SET gold=\"" + gold + "\" WHERE username='" + accountName + "';";
boolean okay = sqlCommand(query, out);
if(okay)
{
//do nothing
}
else
{
out.println("Error: You suck!");
}
disconnectDB();
}
}
| true | true | private stateEnum battleState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.BATTLE)
{
//add a default aresChar incase the getNexrEnemy does not work
Integer Level = playerChar.getLevel();
Item[] itemsHeld = {generateWeapon(Level +1), generateArmor(Level+1)};
int aresHealth = constantHealthBase+(Level+1)*constantPtsPerLevel*constantHealthPerLevel;
int aresStrength = (Level+1)*constantPtsPerLevel*constantStrengthPerLevel;
int aresAgility = (Level+1)*constantPtsPerLevel*constantAgilityPerLevel;
int aresMagic = (Level+1)*constantPtsPerLevel*constantMagicPerLevel;
aresChar = new AresCharacter("Ares", "", Level, aresHealth, aresStrength, aresAgility, aresMagic, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0);
try {
getNextEnemy(playerChar.getLevel(), out);
} catch (SQLException ex) {
}
}
String startPage = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"header\" class=\"grid10\" align=\"center\">\n" +
" %s \n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <br />\n" +
" <p align=\"center\">\n" +
" </p>\n" +
" <div class=\"gridHalf\"> \n";
String statsTable =
" <h2 align=\"center\"> %s </h2>\n" +
" \n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <th> Health </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> %d </th>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String equippedTable1 =
" \n" +
" <h3 align=\"center\"> Equipped </h3>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> Weapon: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n";
String equippedTable2 =
" <tr>\n" +
" <th> Armor: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String betweenCharacters =
" </div>\n" +
" <div class=\"gridHalf\"> \n";
String afterTable =
" \n" +
" </div>\n" +
" <div class=\"grid10\">\n" +
" <div align=\"center\">\n"
+ " <form action=\"Tarsus\" method = \"post\">";
String attackButton =
" <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> <br /> \n" +
" <select name = \"itemSelected\"> \n";
String useButton =
" </select>" +
" <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n";
String lastPart =
" </form>" +
" <div class=\"grid1\"> </div> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
int aresDamage = 0, playerDamage = 0;
//The page clicked was in the battle state, so interpret the button pressed
if(startingState == stateEnum.BATTLE)
{
String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName;
if(valueAttack!=null)
value = valueAttack;
if(valueUse!=null)
{
value=valueUse;
itemName = request.getParameter("itemSelected");
}
if(valueOK!=null)
value=valueOK;
if(!value.equals("OK"))
{
actionEnum playerAction = playerChar.requestAction(request);
actionEnum aresAction = aresChar.requestAction(request);
if((playerAction == actionEnum.ATTACK)&&(aresAction == actionEnum.ATTACK))
{
//find which type of attack the player is using and calculate the damage
if(playerChar.weapon.getStrength()!=0)
{
aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100));
}
if(playerChar.weapon.getAgility()!=0)
{
aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100));
}
if(playerChar.weapon.getMagic()!=0)
{
aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100));
}
//find which type of attack the player is using and calculate the damage
if(aresChar.weapon.getStrength()!=0)
{
playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100));
}
if(aresChar.weapon.getMagic()!=0)
{
playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100));
}
if(aresChar.weapon.getAgility()!=0)
{
playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100));
}
}
//inflict the damage
playerChar.setHealth(playerChar.getHealth() - playerDamage);
aresChar.setHealth(aresChar.getHealth() - aresDamage);
}
//the player has been defeated
else if(playerChar.getHealth()<1)
{
//mark the character as dead in the database
updateCharacter(playerChar, true, out);
disconnectDB();
return stateEnum.PROFILE;
}
//the player defeated the enemy without dying
else if(aresChar.getHealth()<1)
return stateEnum.LEVEL_UP;
}
//print out most of the page
out.printf(startPage,accountName);
out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility());
out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility());
out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility());
out.printf(betweenCharacters);
out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility());
out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility());
out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility());
out.printf(afterTable);
out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage);
//the different ways the page can end
if((playerChar.getHealth()>0) && (aresChar.getHealth()>0))
{
out.printf(attackButton);
for(int i=0; i < playerChar.itemsHeld.length;i++)
{
//change first string, the value parameter, to itemId
if(playerChar.itemsHeld[i]!=null)
out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName());
}
out.printf(useButton);
}
else if(playerChar.getHealth()<1)
{
out.printf("The valiant hero has been killed. <br />\n");
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
else if(aresChar.getHealth()<1)
{
int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8));
gold+=newGold;
updateGold(out);
playerChar.setHealth(playerChar.getMaxHealth());
out.printf("Congradulations you beat your enemy.\n You get %d gold.\n", newGold);
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
out.printf(lastPart);
return stateEnum.BATTLE;
}
| private stateEnum battleState(PrintWriter out, HttpServletRequest request) {
if(startingState != stateEnum.BATTLE)
{
//add a default aresChar incase the getNexrEnemy does not work
Integer Level = playerChar.getLevel();
Item[] itemsHeld = {generateWeapon(Level +1), generateArmor(Level+1)};
int aresHealth = constantHealthBase+(Level+1)*constantPtsPerLevel*constantHealthPerLevel;
int aresStrength = (Level+1)*constantPtsPerLevel*constantStrengthPerLevel;
int aresAgility = (Level+1)*constantPtsPerLevel*constantAgilityPerLevel;
int aresMagic = (Level+1)*constantPtsPerLevel*constantMagicPerLevel;
aresChar = new AresCharacter("Ares", "", Level, aresHealth, aresStrength, aresAgility, aresMagic, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0);
try {
getNextEnemy(playerChar.getLevel(), out);
} catch (SQLException ex) {
}
}
String startPage = "<html>\n" +
" <head>\n" +
" <!-- Call normalize.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Import Font to be used in titles and buttons -->\n" +
" <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" +
" <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" +
" <!-- Call style.css -->\n" +
" <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" +
" <title> Tarsus </title>\n" +
" </head>\n" +
" <body>\n" +
" <div id=\"header\" class=\"grid10\" align=\"center\">\n" +
" %s \n" +
" </div>\n" +
" <div class=\"grid1\"> </div>\n" +
" <div class=\"grid8 centered\">\n" +
" <br />\n" +
" <p align=\"center\">\n" +
" </p>\n" +
" <div class=\"gridHalf\"> \n";
String statsTable =
" <h2 align=\"center\"> %s </h2>\n" +
" \n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <th> Health </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> %d </th>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String equippedTable1 =
" \n" +
" <h3 align=\"center\"> Equipped </h3>\n" +
" <table id=\"table\" align=\"center\">\n" +
" <tr>\n" +
" <td> </td>\n" +
" <th> Name </th>\n" +
" <th> Strength </th>\n" +
" <th> Magic </th>\n" +
" <th> Agility </th>\n" +
" </tr>\n" +
" <tr>\n" +
" <th> Weapon: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n";
String equippedTable2 =
" <tr>\n" +
" <th> Armor: </th>\n" +
" <td> %s </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" <td> %d </td>\n" +
" </tr>\n" +
" </table>\n";
String betweenCharacters =
" </div>\n" +
" <div class=\"gridHalf\"> \n";
String afterTable =
" \n" +
" </div>\n" +
" <div class=\"grid10\">\n" +
" <div align=\"center\">\n"
+ " <form action=\"Tarsus\" method = \"post\">";
String attackButton =
" <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> <br /> \n" +
" <select name = \"itemSelected\"> \n";
String useButton =
" </select>" +
" <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n";
String lastPart =
" </form>" +
" <div class=\"grid1\"> </div> </div>\n" +
" </body>\n" +
" \n" +
"</html>";
int aresDamage = 0, playerDamage = 0;
//The page clicked was in the battle state, so interpret the button pressed
if(startingState == stateEnum.BATTLE)
{
String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName;
if(valueAttack!=null)
value = valueAttack;
if(valueUse!=null)
{
value=valueUse;
itemName = request.getParameter("itemSelected");
}
if(valueOK!=null)
value=valueOK;
if(!value.equals("OK"))
{
actionEnum playerAction = playerChar.requestAction(request);
actionEnum aresAction = aresChar.requestAction(request);
if((playerAction == actionEnum.ATTACK)&&(aresAction == actionEnum.ATTACK))
{
//find which type of attack the player is using and calculate the damage
if(playerChar.weapon.getStrength()!=0)
{
aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100));
}
if(playerChar.weapon.getAgility()!=0)
{
aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100));
}
if(playerChar.weapon.getMagic()!=0)
{
aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100));
}
//find which type of attack the player is using and calculate the damage
if(aresChar.weapon.getStrength()!=0)
{
playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100));
}
if(aresChar.weapon.getMagic()!=0)
{
playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100));
}
if(aresChar.weapon.getAgility()!=0)
{
playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100));
}
}
//inflict the damage
playerChar.setHealth(playerChar.getHealth() - playerDamage);
aresChar.setHealth(aresChar.getHealth() - aresDamage);
}
//the player has been defeated
else if(playerChar.getHealth()<1)
{
//mark the character as dead in the database
updateCharacter(playerChar, true, out);
disconnectDB();
return stateEnum.PROFILE;
}
//the player defeated the enemy without dying
else if(aresChar.getHealth()<1)
return stateEnum.LEVEL_UP;
}
//print out most of the page
out.printf(startPage,accountName);
out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility());
out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility());
out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility());
out.printf(betweenCharacters);
out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility());
out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility());
out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility());
out.printf(afterTable);
out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage);
//the different ways the page can end
if((playerChar.getHealth()>0) && (aresChar.getHealth()>0))
{
out.printf(attackButton);
for(int i=0; i < playerChar.itemsHeld.length;i++)
{
//change first string, the value parameter, to itemId
if(playerChar.itemsHeld[i]!=null)
out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName());
}
out.printf(useButton);
}
else if(playerChar.getHealth()<1)
{
out.printf("The valiant hero has been killed. <br />\n");
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
else if(aresChar.getHealth()<1)
{
int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8));
gold+=newGold;
updateGold(out);
playerChar.setHealth(playerChar.getMaxHealth());
out.printf("CongratulationsCongradulations you beat your enemy.\n You get %d gold.\n", newGold);
out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n");
}
out.printf(lastPart);
return stateEnum.BATTLE;
}
|
diff --git a/modules/jpm-struts1-jar/src/main/java/jpaoletti/jpm/struts/converter/ObjectConverter.java b/modules/jpm-struts1-jar/src/main/java/jpaoletti/jpm/struts/converter/ObjectConverter.java
index e5e8e98..22f3d91 100644
--- a/modules/jpm-struts1-jar/src/main/java/jpaoletti/jpm/struts/converter/ObjectConverter.java
+++ b/modules/jpm-struts1-jar/src/main/java/jpaoletti/jpm/struts/converter/ObjectConverter.java
@@ -1,82 +1,78 @@
package jpaoletti.jpm.struts.converter;
import jpaoletti.jpm.converter.ConverterException;
import jpaoletti.jpm.core.Entity;
import jpaoletti.jpm.core.EntityInstanceWrapper;
import jpaoletti.jpm.core.InstanceId;
import jpaoletti.jpm.core.PMContext;
import jpaoletti.jpm.core.PMException;
import jpaoletti.jpm.struts.CollectionHelper;
/**Converter for integer <br>
* <pre>
* {@code
* <converter class="jpaoletti.jpm.converter.ObjectConverter">
* <operationId>edit</operationId>
* <properties>
* <property name="entity" value="other_entity" />
* <property name="display" value="other_entity_display" />
* <property name="with-null" value="true" />
* <property name="filter" value="jpaoletti.jpm.core.ListFilterXX" />
* <property name="sort-field" value="xxx" /> NOT IMPLEMENTED!
* <property name="sort-direction" value="asc | desc" /> NOT IMPLEMENTED!
* <property name="min-search-size" value="0" />
* </properties>
* </converter>
* }
* </pre>
* @author jpaoletti
* */
public class ObjectConverter extends StrutsEditConverter {
@Override
public Object build(PMContext ctx) throws ConverterException {
try {
final String _entity = getConfig("entity");
final Entity entity = ctx.getPresentationManager().getEntity(_entity);
final String newFieldValue = (String) ctx.getFieldValue();
if (newFieldValue == null || newFieldValue.trim().compareTo("-1") == 0) {
return null;
}
return entity.getDataAccess().getItem(ctx, new InstanceId(newFieldValue));
} catch (PMException ex) {
throw new ConverterException(ex);
}
}
@Override
public Object visualize(PMContext ctx) throws ConverterException {
final String _entity = getConfig("entity");
final Entity entity = ctx.getPresentationManager().getEntity(_entity);
if (entity == null) {
throw new ConverterException("object.converter.entity.cannot.be.null");
}
if (!entity.isIdentified()) {
throw new ConverterException("object.converter.id.cannot.be.null");
}
- final String _display = getConfig("display");
- if (_display == null) {
- throw new ConverterException("object.converter.display.cannot.be.null");
- }
final Object fieldValue = ctx.getFieldValue();
if (fieldValue == null) {
ctx.put("_selected_value", "");
ctx.put("_selected_id", "-1");
- ctx.put("_with_null", false); //false because selected is already null
+ ctx.put("_with_null", getConfig("with-null", "false")); //false because selected is already null
} else {
- final CollectionHelper helper = new CollectionHelper(_display);
+ final CollectionHelper helper = new CollectionHelper(getConfig("display"));
try {
ctx.put("_selected_value", helper.getObjectDisplay(fieldValue));
ctx.put("_selected_id", entity.getDataAccess().getInstanceId(ctx, new EntityInstanceWrapper(fieldValue)).getValue());
ctx.put("_with_null", getConfig("with-null", "false"));
} catch (PMException ex) {
throw new ConverterException("object.converter.cannot.get.id");
}
}
ctx.put("_min_search_size", getConfig("min-search-size", "0"));
ctx.put("_entity", _entity);
- ctx.put("_display", _display);
+ ctx.put("_display", getConfig("display"));
ctx.put("_filter", getConfig("filter"));
return super.visualize("object_converter.jsp?");
}
}
| false | true | public Object visualize(PMContext ctx) throws ConverterException {
final String _entity = getConfig("entity");
final Entity entity = ctx.getPresentationManager().getEntity(_entity);
if (entity == null) {
throw new ConverterException("object.converter.entity.cannot.be.null");
}
if (!entity.isIdentified()) {
throw new ConverterException("object.converter.id.cannot.be.null");
}
final String _display = getConfig("display");
if (_display == null) {
throw new ConverterException("object.converter.display.cannot.be.null");
}
final Object fieldValue = ctx.getFieldValue();
if (fieldValue == null) {
ctx.put("_selected_value", "");
ctx.put("_selected_id", "-1");
ctx.put("_with_null", false); //false because selected is already null
} else {
final CollectionHelper helper = new CollectionHelper(_display);
try {
ctx.put("_selected_value", helper.getObjectDisplay(fieldValue));
ctx.put("_selected_id", entity.getDataAccess().getInstanceId(ctx, new EntityInstanceWrapper(fieldValue)).getValue());
ctx.put("_with_null", getConfig("with-null", "false"));
} catch (PMException ex) {
throw new ConverterException("object.converter.cannot.get.id");
}
}
ctx.put("_min_search_size", getConfig("min-search-size", "0"));
ctx.put("_entity", _entity);
ctx.put("_display", _display);
ctx.put("_filter", getConfig("filter"));
return super.visualize("object_converter.jsp?");
}
| public Object visualize(PMContext ctx) throws ConverterException {
final String _entity = getConfig("entity");
final Entity entity = ctx.getPresentationManager().getEntity(_entity);
if (entity == null) {
throw new ConverterException("object.converter.entity.cannot.be.null");
}
if (!entity.isIdentified()) {
throw new ConverterException("object.converter.id.cannot.be.null");
}
final Object fieldValue = ctx.getFieldValue();
if (fieldValue == null) {
ctx.put("_selected_value", "");
ctx.put("_selected_id", "-1");
ctx.put("_with_null", getConfig("with-null", "false")); //false because selected is already null
} else {
final CollectionHelper helper = new CollectionHelper(getConfig("display"));
try {
ctx.put("_selected_value", helper.getObjectDisplay(fieldValue));
ctx.put("_selected_id", entity.getDataAccess().getInstanceId(ctx, new EntityInstanceWrapper(fieldValue)).getValue());
ctx.put("_with_null", getConfig("with-null", "false"));
} catch (PMException ex) {
throw new ConverterException("object.converter.cannot.get.id");
}
}
ctx.put("_min_search_size", getConfig("min-search-size", "0"));
ctx.put("_entity", _entity);
ctx.put("_display", getConfig("display"));
ctx.put("_filter", getConfig("filter"));
return super.visualize("object_converter.jsp?");
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/funlib/EdgeSeq.java b/src/de/uni_koblenz/jgralab/greql2/funlib/EdgeSeq.java
index d81481ca7..9f4720792 100644
--- a/src/de/uni_koblenz/jgralab/greql2/funlib/EdgeSeq.java
+++ b/src/de/uni_koblenz/jgralab/greql2/funlib/EdgeSeq.java
@@ -1,146 +1,146 @@
/*
* JGraLab - The Java Graph Laboratory
*
* Copyright (C) 2006-2011 Institute for Software Technology
* University of Koblenz-Landau, Germany
* [email protected]
*
* For bug reports, documentation and further information, visit
*
* http://jgralab.uni-koblenz.de
*
* 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 program or an Eclipse
* plugin), 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. Corresponding Source for a
* non-source form of such a combination shall include the source code for
* the parts of JGraLab used as well as that of the covered work.
*/
package de.uni_koblenz.jgralab.greql2.funlib;
import java.util.ArrayList;
import de.uni_koblenz.jgralab.AttributedElement;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.graphmarker.AbstractGraphMarker;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.WrongFunctionParameterException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueImpl;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueSet;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueType;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTypeCollection;
/**
* Returns (a part of) the edge sequence of the graph
*
* <dl>
* <dt><b>GReQL-signature</b></dt>
* <dd><code>List<EDGE> edges(EDGE start, EDGE end)</code></dd>
* <code>List<EDGE> edges(EDGE start, EDGE end, tc:TYPECOLLECTION)</code>
* </dd>
* <dd> </dd>
* </dl>
* <dl>
* <dt></dt>
* <dd>
* <dl>
* <dt><b>Parameters:</b></dt>
* <dd><code>start</code> - the first edge of the subsequence of Eseq to return</dd>
* <dd><code>end</code> - the last rdge of the subsequence of Eseq to return</dd>
* <dt><b>Returns:</b></dt>
* <dd>the subsequence of Eseq containing all edges between start and end
* (including both)</dd>
* </dl>
* </dd>
* </dl>
*
* @see VertexSeq
* @author [email protected]
*
*/
public class EdgeSeq extends Greql2Function {
{
JValueType[][] x = {
{ JValueType.EDGE, JValueType.EDGE, JValueType.COLLECTION },
{ JValueType.EDGE, JValueType.EDGE, JValueType.TYPECOLLECTION,
JValueType.COLLECTION } };
signatures = x;
description = "Returns the global edge sequence from the 1st to the 2nd given edge.\n"
+ "The edge types may be restricted by a type collection.";
Category[] c = { Category.GRAPH };
categories = c;
}
@Override
public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
JValueSet edges = new JValueSet();
Edge start = arguments[0].toEdge();
Edge end = arguments[1].toEdge();
Edge current = start;
switch (checkArguments(arguments)) {
case 0:
while (current != null) {
edges.add(new JValueImpl(current));
if (current == end) {
return edges;
}
- current = current.getNextIncidence();
+ current = current.getNextEdge();
}
return edges;
case 1:
JValueTypeCollection tc = (JValueTypeCollection) arguments[2];
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
edges.add(new JValueImpl(current));
}
if (current == end) {
return edges;
}
- current = current.getNextIncidence();
+ current = current.getNextEdge();
}
return edges;
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
@Override
public long getEstimatedCosts(ArrayList<Long> inElements) {
return 1000;
}
@Override
public double getSelectivity() {
return 0.2;
}
@Override
public long getEstimatedCardinality(int inElements) {
return 100;
}
}
| false | true | public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
JValueSet edges = new JValueSet();
Edge start = arguments[0].toEdge();
Edge end = arguments[1].toEdge();
Edge current = start;
switch (checkArguments(arguments)) {
case 0:
while (current != null) {
edges.add(new JValueImpl(current));
if (current == end) {
return edges;
}
current = current.getNextIncidence();
}
return edges;
case 1:
JValueTypeCollection tc = (JValueTypeCollection) arguments[2];
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
edges.add(new JValueImpl(current));
}
if (current == end) {
return edges;
}
current = current.getNextIncidence();
}
return edges;
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
| public JValue evaluate(Graph graph,
AbstractGraphMarker<AttributedElement> subgraph, JValue[] arguments)
throws EvaluateException {
JValueSet edges = new JValueSet();
Edge start = arguments[0].toEdge();
Edge end = arguments[1].toEdge();
Edge current = start;
switch (checkArguments(arguments)) {
case 0:
while (current != null) {
edges.add(new JValueImpl(current));
if (current == end) {
return edges;
}
current = current.getNextEdge();
}
return edges;
case 1:
JValueTypeCollection tc = (JValueTypeCollection) arguments[2];
while (current != null) {
if (tc.acceptsType(current.getAttributedElementClass())) {
edges.add(new JValueImpl(current));
}
if (current == end) {
return edges;
}
current = current.getNextEdge();
}
return edges;
default:
throw new WrongFunctionParameterException(this, arguments);
}
}
|
diff --git a/src/main/java/com/github/pchudzik/gae/test/config/SpringBeans.java b/src/main/java/com/github/pchudzik/gae/test/config/SpringBeans.java
index c13df44..d0604e5 100644
--- a/src/main/java/com/github/pchudzik/gae/test/config/SpringBeans.java
+++ b/src/main/java/com/github/pchudzik/gae/test/config/SpringBeans.java
@@ -1,58 +1,59 @@
package com.github.pchudzik.gae.test.config;
import org.datanucleus.api.jpa.PersistenceProviderImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* User: pawel
* Date: 20.07.13
* Time: 11:15
*/
@Configuration
@EnableTransactionManagement
@EnableLoadTimeWeaving
public class SpringBeans {
@Bean
public LoadTimeWeaver loadTimeWeaver() {
return new SimpleLoadTimeWeaver();
}
@Bean(name = "entityManagerFactory")
public EntityManagerFactory getEntityManagerFactorySpringWay() {
Map<String, String> jpaProperties = new HashMap<String, String>(){{
put("datanucleus.NontransactionalRead", "true");
put("datanucleus.NontransactionalWrite", "true");
put("datanucleus.ConnectionURL", "appengine");
put("datanucleus.singletonEMFForName", "true");
put("datanucleus.metadata.allowLoadAtRuntime", "true"); //magic property not mentioned in gea docs but required when working with maven
}};
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
+ entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
entityManagerFactoryBean.setPersistenceProviderClass(PersistenceProviderImpl.class);
entityManagerFactoryBean.setPackagesToScan("com.github.pchudzik.gae.test.domain");
entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver());
entityManagerFactoryBean.afterPropertiesSet();
EntityManagerFactory result = entityManagerFactoryBean.getObject();
return result;
}
@Bean @Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
| true | true | public EntityManagerFactory getEntityManagerFactorySpringWay() {
Map<String, String> jpaProperties = new HashMap<String, String>(){{
put("datanucleus.NontransactionalRead", "true");
put("datanucleus.NontransactionalWrite", "true");
put("datanucleus.ConnectionURL", "appengine");
put("datanucleus.singletonEMFForName", "true");
put("datanucleus.metadata.allowLoadAtRuntime", "true"); //magic property not mentioned in gea docs but required when working with maven
}};
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPersistenceProviderClass(PersistenceProviderImpl.class);
entityManagerFactoryBean.setPackagesToScan("com.github.pchudzik.gae.test.domain");
entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver());
entityManagerFactoryBean.afterPropertiesSet();
EntityManagerFactory result = entityManagerFactoryBean.getObject();
return result;
}
| public EntityManagerFactory getEntityManagerFactorySpringWay() {
Map<String, String> jpaProperties = new HashMap<String, String>(){{
put("datanucleus.NontransactionalRead", "true");
put("datanucleus.NontransactionalWrite", "true");
put("datanucleus.ConnectionURL", "appengine");
put("datanucleus.singletonEMFForName", "true");
put("datanucleus.metadata.allowLoadAtRuntime", "true"); //magic property not mentioned in gea docs but required when working with maven
}};
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
entityManagerFactoryBean.setPersistenceProviderClass(PersistenceProviderImpl.class);
entityManagerFactoryBean.setPackagesToScan("com.github.pchudzik.gae.test.domain");
entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver());
entityManagerFactoryBean.afterPropertiesSet();
EntityManagerFactory result = entityManagerFactoryBean.getObject();
return result;
}
|
diff --git a/openid-connect-client/src/main/java/org/mitre/oauth2/filter/IntrospectingTokenService.java b/openid-connect-client/src/main/java/org/mitre/oauth2/filter/IntrospectingTokenService.java
index d43b8fdd..284f7509 100644
--- a/openid-connect-client/src/main/java/org/mitre/oauth2/filter/IntrospectingTokenService.java
+++ b/openid-connect-client/src/main/java/org/mitre/oauth2/filter/IntrospectingTokenService.java
@@ -1,201 +1,201 @@
package org.mitre.oauth2.filter;
import com.google.common.collect.Sets;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
public class IntrospectingTokenService implements ResourceServerTokenServices {
private String clientId;
private String clientSecret;
private String introspectionUrl;
// Inner class to store in the hash map
private class TokenCacheObject { OAuth2AccessToken token; OAuth2Authentication auth;
private TokenCacheObject(OAuth2AccessToken token, OAuth2Authentication auth) {
this.token = token;
this.auth = auth;
}
}
private Map<String, TokenCacheObject> authCache = new HashMap<String, TokenCacheObject>();
public String getIntrospectionUrl() {
return introspectionUrl;
}
public void setIntrospectionUrl(String introspectionUrl) {
this.introspectionUrl = introspectionUrl;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
// Check if there is a token and authentication in the cache
// and check if it is not expired.
private TokenCacheObject checkCache(String key) {
if(authCache.containsKey(key)) {
TokenCacheObject tco = authCache.get(key);
if (tco.token.getExpiration().after(new Date())) {
return tco;
} else {
// if the token is expired, don't keep things around.
authCache.remove(key);
}
}
return null;
}
private AuthorizationRequest createAuthRequest(final JsonObject token) {
AuthorizationRequest authReq = new AuthorizationRequestImpl(token);
return authReq;
}
// create a default authentication object with authority ROLE_API
private Authentication createAuthentication(JsonObject token){
// TODO: user_id is going to go away. Will have to fix.
return new PreAuthenticatedAuthenticationToken(token.get("sub").getAsString(), null, AuthorityUtils.createAuthorityList("ROLE_API"));
}
private OAuth2AccessToken createAccessToken(final JsonObject token, final String tokenString){
OAuth2AccessToken accessToken = new OAuth2AccessTokenImpl(token, tokenString);
return accessToken;
}
// Validate a token string against the introspection endpoint,
// then parse it and store it in the local cache. Return true on
// sucess, false otherwise.
private boolean parseToken(String accessToken) {
String validatedToken = null;
// Use the SpringFramework RestTemplate to send the request to the endpoint
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("token",accessToken);
form.add("client_id", this.clientId);
- form.add("client_scret", this.clientSecret);
+ form.add("client_secret", this.clientSecret);
try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
} catch (RestClientException rce) {
// TODO: LOG THIS!?
LoggerFactory.getLogger(IntrospectingTokenService.class).error("validateToken", rce);
}
if (validatedToken != null) {
// parse the json
JsonElement jsonRoot = new JsonParser().parse(validatedToken);
if (!jsonRoot.isJsonObject()) {
return false; // didn't get a proper JSON object
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// report an error?
return false;
}
if (!tokenResponse.get("valid").getAsBoolean()){
// non-valid token
return false;
}
// create an OAuth2Authentication
OAuth2Authentication auth = new OAuth2Authentication(createAuthRequest(tokenResponse), null);
// create an OAuth2AccessToken
OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);
if (token.getExpiration().after(new Date())){
// Store them in the cache
authCache.put(accessToken, new TokenCacheObject(token,auth));
return true;
}
}
// If we never put a token and an authentication in the cache...
return false;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
// First check if the in memory cache has an Authentication object, and that it is still valid
// If Valid, return it
TokenCacheObject cacheAuth = checkCache(accessToken);
if (cacheAuth != null) {
return cacheAuth.auth;
} else {
if (parseToken(accessToken)) {
cacheAuth = authCache.get(accessToken);
if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) {
return cacheAuth.auth;
} else {
return null;
}
} else {
return null;
}
}
}
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
// First check if the in memory cache has a Token object, and that it is still valid
// If Valid, return it
TokenCacheObject cacheAuth = checkCache(accessToken);
if (cacheAuth != null) {
return cacheAuth.token;
} else {
if (parseToken(accessToken)) {
cacheAuth = authCache.get(accessToken);
if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) {
return cacheAuth.token;
} else {
return null;
}
} else {
return null;
}
}
}
}
| true | true | private boolean parseToken(String accessToken) {
String validatedToken = null;
// Use the SpringFramework RestTemplate to send the request to the endpoint
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("token",accessToken);
form.add("client_id", this.clientId);
form.add("client_scret", this.clientSecret);
try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
} catch (RestClientException rce) {
// TODO: LOG THIS!?
LoggerFactory.getLogger(IntrospectingTokenService.class).error("validateToken", rce);
}
if (validatedToken != null) {
// parse the json
JsonElement jsonRoot = new JsonParser().parse(validatedToken);
if (!jsonRoot.isJsonObject()) {
return false; // didn't get a proper JSON object
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// report an error?
return false;
}
if (!tokenResponse.get("valid").getAsBoolean()){
// non-valid token
return false;
}
// create an OAuth2Authentication
OAuth2Authentication auth = new OAuth2Authentication(createAuthRequest(tokenResponse), null);
// create an OAuth2AccessToken
OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);
if (token.getExpiration().after(new Date())){
// Store them in the cache
authCache.put(accessToken, new TokenCacheObject(token,auth));
return true;
}
}
// If we never put a token and an authentication in the cache...
return false;
}
| private boolean parseToken(String accessToken) {
String validatedToken = null;
// Use the SpringFramework RestTemplate to send the request to the endpoint
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("token",accessToken);
form.add("client_id", this.clientId);
form.add("client_secret", this.clientSecret);
try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
} catch (RestClientException rce) {
// TODO: LOG THIS!?
LoggerFactory.getLogger(IntrospectingTokenService.class).error("validateToken", rce);
}
if (validatedToken != null) {
// parse the json
JsonElement jsonRoot = new JsonParser().parse(validatedToken);
if (!jsonRoot.isJsonObject()) {
return false; // didn't get a proper JSON object
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// report an error?
return false;
}
if (!tokenResponse.get("valid").getAsBoolean()){
// non-valid token
return false;
}
// create an OAuth2Authentication
OAuth2Authentication auth = new OAuth2Authentication(createAuthRequest(tokenResponse), null);
// create an OAuth2AccessToken
OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);
if (token.getExpiration().after(new Date())){
// Store them in the cache
authCache.put(accessToken, new TokenCacheObject(token,auth));
return true;
}
}
// If we never put a token and an authentication in the cache...
return false;
}
|
diff --git a/src/android/Settings.java b/src/android/Settings.java
index 08082e5..7670faa 100644
--- a/src/android/Settings.java
+++ b/src/android/Settings.java
@@ -1,61 +1,61 @@
package com.codeb.cordova.plugins.settings;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.wifi.WifiManager;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.os.Looper;
import android.util.Log;
/**
* This class echoes a string called from JavaScript.
*/
public class Settings extends CordovaPlugin {
private static final String LOG_TAG = "Settings Plugin";
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
JSONObject arg_object = args.getJSONObject(0);
if (action.equals("getBluetooth")) {
String message = arg_object.getString("action");
- this.getBluetooth(message, callbackContext);
+ this.getBluetooth(callbackContext);
return true;
} else if (action.equals("setBluetooth")) {
String message = arg_object.getString("action");
- this.getBluetooth(message, callbackContext);
+ this.setBluetooth(message, callbackContext);
return true;
}
return false;
} catch(Exception e) {
callbackContext.error(e.getMessage());
return false;
}
}
private void setBluetooth(String action, CallbackContext callbackContext) {
Log.d(LOG_TAG, "Execute setBluetooth");
if (action != null && action.length() > 0) {
callbackContext.success(action);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
private void getBluetooth(CallbackContext callbackContext) {
Looper.prepare();
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean result = bluetoothAdapter.isEnabled();
Log.d(LOG_TAG, "Bluetooth enabled: " + result);
return result;
}
}
| false | true | public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
JSONObject arg_object = args.getJSONObject(0);
if (action.equals("getBluetooth")) {
String message = arg_object.getString("action");
this.getBluetooth(message, callbackContext);
return true;
} else if (action.equals("setBluetooth")) {
String message = arg_object.getString("action");
this.getBluetooth(message, callbackContext);
return true;
}
return false;
} catch(Exception e) {
callbackContext.error(e.getMessage());
return false;
}
}
| public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
JSONObject arg_object = args.getJSONObject(0);
if (action.equals("getBluetooth")) {
String message = arg_object.getString("action");
this.getBluetooth(callbackContext);
return true;
} else if (action.equals("setBluetooth")) {
String message = arg_object.getString("action");
this.setBluetooth(message, callbackContext);
return true;
}
return false;
} catch(Exception e) {
callbackContext.error(e.getMessage());
return false;
}
}
|
diff --git a/plugins/com.aptana.ide.update/src/com/aptana/ide/internal/update/manager/AbstractPluginManager.java b/plugins/com.aptana.ide.update/src/com/aptana/ide/internal/update/manager/AbstractPluginManager.java
index eb17655b..8258ef5f 100644
--- a/plugins/com.aptana.ide.update/src/com/aptana/ide/internal/update/manager/AbstractPluginManager.java
+++ b/plugins/com.aptana.ide.update/src/com/aptana/ide/internal/update/manager/AbstractPluginManager.java
@@ -1,511 +1,514 @@
package com.aptana.ide.internal.update.manager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import com.aptana.ide.update.Activator;
import com.aptana.ide.update.IPreferenceConstants;
import com.aptana.ide.update.manager.IPluginManager;
import com.aptana.ide.update.manager.Plugin;
import com.aptana.ide.update.manager.PluginListener;
/**
* A base class for plugin managers that performs the common tasks of managing listeners, grabbing the remote plugin
* list.
*
* @author cwilliams
*/
public abstract class AbstractPluginManager implements IPluginManager, IPreferenceChangeListener
{
protected static final String FEATURE_IU_SUFFIX = ".feature.group"; //$NON-NLS-1$
private static final String CACHED_PLUGINS_XML_FILENAME = "cached_plugins.xml"; //$NON-NLS-1$
private static final int DAY = 1000 * 60 * 60 * 24;
private final Set<PluginListener> listeners = new HashSet<PluginListener>();
private String fgRemotePluginsURL;
private long lastUpdated = -1;
protected AbstractPluginManager()
{
IEclipsePreferences prefs = (new InstanceScope()).getNode(Activator.PLUGIN_ID);
prefs.addPreferenceChangeListener(this);
}
public void addListener(PluginListener listener)
{
listeners.add(listener);
}
public Collection<PluginListener> getListeners()
{
return listeners;
}
public void removeListener(PluginListener pluginsListener)
{
listeners.remove(pluginsListener);
}
public List<Plugin> getRemotePlugins()
{
// returns the local cached copy of feed first, then schedules a job to
// grab the latest feed from remote site
List<Plugin> plugins = new ArrayList<Plugin>();
try
{
InputStream xml = (InputStream) getLocalURL().getContent();
plugins = parseXML(xml);
// modifies the Plugin objects to use the local cached locations for
// the images
loadImages(plugins);
}
catch (IOException e)
{
plugins = new ArrayList<Plugin>();
}
if (haventUpdatedInADay())
{
scheduleLoadOfRemotePluginListing();
}
return plugins;
}
private void scheduleLoadOfRemotePluginListing()
{
Job job = new Job(Messages.PluginsManager_RemoteJobTitle)
{
protected IStatus run(IProgressMonitor monitor)
{
try
{
InputStream in = (InputStream) getURL(getRemotePluginsURL()).getContent();
// TODO Fix STU-2881 (partially) by iterating through the plugins and checking their update
// sites for the feature id and then re-writing the correct plugin version in
// cache the plugins_2.0.xml file
saveCache(in);
// caches the images referenced in the xml files
cacheImages();
}
catch (IOException e)
{
error(e);
return Status.CANCEL_STATUS;
}
finally
{
lastUpdated = System.currentTimeMillis();
}
// fires the corresponding event
for (PluginListener listener : listeners)
{
listener.remotePluginsRefreshed();
}
return Status.OK_STATUS;
}
};
job.setSystem(true);
job.schedule(10000); // schedules a 10-second delay
}
protected String getRemotePluginsURL()
{
if (fgRemotePluginsURL == null)
{
// for testing purpose, the plugins.xml file location could be driven by a
// command line flag
String location = System.getProperty("PLUGINS_XML_LOCATION"); //$NON-NLS-1$
if (location == null || location.length() == 0)
{
// Grab location from a pref!
String defaultURL = (new DefaultScope()).getNode(
Activator.PLUGIN_ID).get(
IPreferenceConstants.REMOTE_PLUGIN_LISTING_URL, ""); //$NON-NLS-1$
location = Platform.getPreferencesService().getString(
Activator.PLUGIN_ID,
IPreferenceConstants.REMOTE_PLUGIN_LISTING_URL,
defaultURL, null);
}
fgRemotePluginsURL = location;
}
return fgRemotePluginsURL;
}
/**
* Caches the remote images that plug-ins are referencing locally for faster loading.
*/
private void cacheImages()
{
// FIXME This seems like UI stuff that should not be in the plugin manager code!
// first parses the cached xml file
List<Plugin> plugins = new ArrayList<Plugin>();
try
{
InputStream xml = (InputStream) getLocalCacheURL().getContent();
plugins = parseXML(xml);
}
catch (IOException e)
{
plugins = new ArrayList<Plugin>();
}
ImageLoader loader = new ImageLoader();
IPath directory = Activator.getDefault().getStateLocation();
String imagePath;
ImageDescriptor image;
String id, ext;
File newFile;
Map<String, String> urlMap = new HashMap<String, String>();
for (Plugin plugin : plugins)
{
imagePath = plugin.getImagePath();
if (imagePath != null)
{
OutputStream out = null;
try
{
// loads the image
image = Activator.getImageDescriptor(imagePath);
if (image == null)
{
image = ImageDescriptor.createFromURL(getURL(imagePath));
}
loader.data = new ImageData[1];
loader.data[0] = image.getImageData();
+ if (loader.data[0] == null) {
+ continue;
+ }
// caches the image locally
id = plugin.getId();
ext = getExtension(imagePath);
newFile = directory.append(id + ext).toFile();
newFile.createNewFile();
out = new FileOutputStream(newFile);
loader.save(out, getImageFormat(ext));
// stores the mapping between the two paths
urlMap.put(imagePath, newFile.toString());
}
catch (IOException e)
{
error(e);
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException e)
{
// ignore
}
}
}
}
// saves the mapping
saveImageURLMap(urlMap);
}
private static void saveImageURLMap(Map<String, String> map)
{
IEclipsePreferences prefs = (new InstanceScope()).getNode(Activator.PLUGIN_ID);
Iterator<String> iter = map.keySet().iterator();
String key;
while (iter.hasNext())
{
key = iter.next();
prefs.put(key, map.get(key));
}
}
private static String getExtension(String filename)
{
int index = filename.lastIndexOf("."); //$NON-NLS-1$
return index < 0 ? "" : filename.substring(index); //$NON-NLS-1$
}
private static int getImageFormat(String extension)
{
if (extension.equals(".png")) { //$NON-NLS-1$
return SWT.IMAGE_PNG;
}
if (extension.equals(".gif")) { //$NON-NLS-1$
return SWT.IMAGE_GIF;
}
if (extension.equals(".bmp")) { //$NON-NLS-1$
return SWT.IMAGE_BMP;
}
if (extension.equals(".jpg")) { //$NON-NLS-1$
return SWT.IMAGE_JPEG;
}
return SWT.IMAGE_ICO;
}
private boolean haventUpdatedInADay()
{
return lastUpdated < System.currentTimeMillis() - DAY;
}
private URL getURL(String location) throws MalformedURLException
{
try
{
return new URL(location);
}
catch (MalformedURLException e)
{
return (new File(location)).toURI().toURL();
}
}
private static List<Plugin> parseXML(InputStream xml)
{
try
{
XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
PluginsContentHandler handler = new PluginsContentHandler();
reader.setContentHandler(handler);
reader.parse(new InputSource(xml));
// TODO Write out a copy of the contents to the local file if we
// grabbed from remote URL?
return handler.getPlugins();
}
catch (IOException e)
{
error(e);
}
catch (SAXException e)
{
error(e);
}
catch (ParserConfigurationException e)
{
error(e);
}
finally
{
if (xml != null)
{
try
{
xml.close();
}
catch (IOException e)
{
// ignore
}
}
}
// some exception occurred; returns an empty list
return new ArrayList<Plugin>();
}
private static void loadImages(List<Plugin> plugins)
{
IPreferencesService service = Platform.getPreferencesService();
String imagePath, cachedPath;
for (Plugin plugin : plugins)
{
imagePath = plugin.getImagePath();
if (imagePath != null)
{
// finds the local cached image location
cachedPath = service.getString(Activator.PLUGIN_ID, imagePath, "", null); //$NON-NLS-1$
if (cachedPath != null && cachedPath.length() > 0)
{
plugin.setImagePath(cachedPath);
}
}
}
}
/**
* Returns the URL for local cached copy, or if that fails, then returns the original URL packaged in the plug-in.
*
* @return the URL
* @throws MalformedURLException
*/
private URL getLocalURL() throws MalformedURLException
{
try
{
return getLocalCacheURL();
}
catch (MalformedURLException e)
{
return getOriginalFileURL();
}
}
private URL getLocalCacheURL() throws MalformedURLException
{
return getLocalCacheFile().toURI().toURL();
}
private File getLocalCacheFile()
{
IPath statePath = Activator.getDefault().getStateLocation().append(getCacheFilename());
File file = statePath.toFile();
if (!file.exists())
{
try
{
file.createNewFile();
// caches the file
copyOriginalToCache();
}
catch (IOException e)
{
error(e);
}
}
return file;
}
private String getCacheFilename()
{
return CACHED_PLUGINS_XML_FILENAME;
}
private URL getOriginalFileURL() throws MalformedURLException
{
String defaultURL = (new DefaultScope()).getNode(Activator.PLUGIN_ID)
.get(IPreferenceConstants.LOCAL_PLUGIN_LISTING_URL, ""); //$NON-NLS-1$
return new URL(Platform.getPreferencesService().getString(
Activator.PLUGIN_ID,
IPreferenceConstants.LOCAL_PLUGIN_LISTING_URL, defaultURL, null));
}
/**
* Copy the contents of the original local XML feed over to the cached file in the plugin's state location.
*
* @param file
*/
private void copyOriginalToCache()
{
try
{
InputStream in = (InputStream) getOriginalFileURL().getContent();
saveCache(in);
}
catch (IOException e)
{
error(e);
}
}
private static void error(Exception e)
{
Activator.log(IStatus.ERROR, e.getMessage(), e);
}
/**
* Copy contents from an InputStream to the local cache file.
*
* @param xml
* the input stream
*/
private void saveCache(InputStream xml)
{
// FIXME: Copy using byte array buffers to speed things up, not byte by
// byte like we do here
File file = getLocalCacheFile();
OutputStream writer = null;
try
{
writer = new FileOutputStream(file);
int b = -1;
while ((b = xml.read()) != -1)
{
writer.write(b);
}
}
catch (FileNotFoundException e)
{
error(e);
}
catch (IOException e)
{
error(e);
}
finally
{
try
{
if (xml != null)
xml.close();
}
catch (IOException e)
{
// ignore
}
try
{
if (writer != null)
writer.close();
}
catch (IOException e)
{
// ignore
}
}
}
public void preferenceChange(PreferenceChangeEvent event) {
String key = event.getKey();
if (IPreferenceConstants.REMOTE_PLUGIN_LISTING_URL.equals(key))
{
fgRemotePluginsURL = null;
scheduleLoadOfRemotePluginListing();
}
else if (IPreferenceConstants.LOCAL_PLUGIN_LISTING_URL.equals(key))
{
File localCache = getLocalCacheFile();
if (localCache != null)
localCache.delete();
}
}
}
| true | true | private void cacheImages()
{
// FIXME This seems like UI stuff that should not be in the plugin manager code!
// first parses the cached xml file
List<Plugin> plugins = new ArrayList<Plugin>();
try
{
InputStream xml = (InputStream) getLocalCacheURL().getContent();
plugins = parseXML(xml);
}
catch (IOException e)
{
plugins = new ArrayList<Plugin>();
}
ImageLoader loader = new ImageLoader();
IPath directory = Activator.getDefault().getStateLocation();
String imagePath;
ImageDescriptor image;
String id, ext;
File newFile;
Map<String, String> urlMap = new HashMap<String, String>();
for (Plugin plugin : plugins)
{
imagePath = plugin.getImagePath();
if (imagePath != null)
{
OutputStream out = null;
try
{
// loads the image
image = Activator.getImageDescriptor(imagePath);
if (image == null)
{
image = ImageDescriptor.createFromURL(getURL(imagePath));
}
loader.data = new ImageData[1];
loader.data[0] = image.getImageData();
// caches the image locally
id = plugin.getId();
ext = getExtension(imagePath);
newFile = directory.append(id + ext).toFile();
newFile.createNewFile();
out = new FileOutputStream(newFile);
loader.save(out, getImageFormat(ext));
// stores the mapping between the two paths
urlMap.put(imagePath, newFile.toString());
}
catch (IOException e)
{
error(e);
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException e)
{
// ignore
}
}
}
}
// saves the mapping
saveImageURLMap(urlMap);
}
| private void cacheImages()
{
// FIXME This seems like UI stuff that should not be in the plugin manager code!
// first parses the cached xml file
List<Plugin> plugins = new ArrayList<Plugin>();
try
{
InputStream xml = (InputStream) getLocalCacheURL().getContent();
plugins = parseXML(xml);
}
catch (IOException e)
{
plugins = new ArrayList<Plugin>();
}
ImageLoader loader = new ImageLoader();
IPath directory = Activator.getDefault().getStateLocation();
String imagePath;
ImageDescriptor image;
String id, ext;
File newFile;
Map<String, String> urlMap = new HashMap<String, String>();
for (Plugin plugin : plugins)
{
imagePath = plugin.getImagePath();
if (imagePath != null)
{
OutputStream out = null;
try
{
// loads the image
image = Activator.getImageDescriptor(imagePath);
if (image == null)
{
image = ImageDescriptor.createFromURL(getURL(imagePath));
}
loader.data = new ImageData[1];
loader.data[0] = image.getImageData();
if (loader.data[0] == null) {
continue;
}
// caches the image locally
id = plugin.getId();
ext = getExtension(imagePath);
newFile = directory.append(id + ext).toFile();
newFile.createNewFile();
out = new FileOutputStream(newFile);
loader.save(out, getImageFormat(ext));
// stores the mapping between the two paths
urlMap.put(imagePath, newFile.toString());
}
catch (IOException e)
{
error(e);
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException e)
{
// ignore
}
}
}
}
// saves the mapping
saveImageURLMap(urlMap);
}
|
diff --git a/PullPit/src/kea/kme/pullpit/server/persistence/ShowHandler.java b/PullPit/src/kea/kme/pullpit/server/persistence/ShowHandler.java
index 4cab772..eded52b 100644
--- a/PullPit/src/kea/kme/pullpit/server/persistence/ShowHandler.java
+++ b/PullPit/src/kea/kme/pullpit/server/persistence/ShowHandler.java
@@ -1,81 +1,80 @@
package kea.kme.pullpit.server.persistence;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import kea.kme.pullpit.client.objects.Band;
import kea.kme.pullpit.client.objects.Show;
import kea.kme.pullpit.client.objects.Venue;
import java.util.logging.Logger;
public class ShowHandler {
private static final Logger log = Logger.getLogger(ShowHandler.class
.getName());
public static Show[] getShows(int offset, int limit, String orderBy)
throws SQLException {
Connection con = DBConnector.getInstance().getConnection();
HashMap<Integer, Show> results = new HashMap<Integer, Show>();
Statement s = con.createStatement();
String sql = "SELECT shows.*, venues.*, bands.bandID, bands.bandName "
+ "FROM ((shows LEFT OUTER JOIN showvenues ON shows.showID = showvenues.showID) "
+ "LEFT OUTER JOIN venues ON showvenues.venueID = venues.venueID) "
+ "JOIN bands ON bands.bandID = shows.bandID "
+ "ORDER BY " + orderBy + " LIMIT " + offset + "," + limit;
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
// Uses column-name to avoid confusion when queries are joined
int showID = rs.getInt("showID");
int bandID = rs.getInt("bandID");
String bandName = rs.getString("bandName");
Date date = rs.getDate("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(date);
int state = rs.getInt("state");
String comments = rs.getString("comments");
Date lastEdit = rs.getDate("lastEdit");
SimpleDateFormat lastEditFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
String lastEditString = lastEditFormat.format(lastEdit);
// Handles shows with no Venues
if (rs.getString("venueName") == null) {
results.put(showID, new Show(showID,
new Band(bandID, bandName), dateString, state, comments,
lastEditString));
// Handles shows with Venues
} else {
// Handles shows with one or more venues
if (results.containsKey(showID)) {
// Creates temp array to hold existing venues
Venue[] temp = results.get(showID).getVenues();
// Creates new array, 1 longer than temp
Venue[] newTemp = new Venue[temp.length + 1];
// Inserts new Venue on index 0 (always same place no matter how many venues in current show
newTemp[0] = new Venue(rs.getInt("venueID"),
rs.getString("venueName"));
// Moves the old venues one place up
- for (int i = 1; i <= newTemp.length; i++) {
+ for (int i = 1; i < newTemp.length; i++) {
newTemp[i] = temp[i - 1];
}
results.get(showID).setVenues(newTemp);
} else {
// Handles new shows
Venue[] venues = new Venue[1];
venues[0] = new Venue(rs.getInt("venueID"), rs.getString("venueName"));
log.info("Adding new venue, " + venues[0].toString());
- results.put(
- showID,
- new Show(showID, new Band(bandID, bandName), dateString,
- state, comments, lastEditString, venues));
+ Show newShow = new Show(showID, new Band(bandID, bandName), dateString,
+ state, comments, lastEditString, venues);
+ results.put(showID, newShow);
}
}
}
rs.close();
log.info("returning " + results.size() + "shows");
return results.values().toArray(new Show[results.size()]);
}
}
| false | true | public static Show[] getShows(int offset, int limit, String orderBy)
throws SQLException {
Connection con = DBConnector.getInstance().getConnection();
HashMap<Integer, Show> results = new HashMap<Integer, Show>();
Statement s = con.createStatement();
String sql = "SELECT shows.*, venues.*, bands.bandID, bands.bandName "
+ "FROM ((shows LEFT OUTER JOIN showvenues ON shows.showID = showvenues.showID) "
+ "LEFT OUTER JOIN venues ON showvenues.venueID = venues.venueID) "
+ "JOIN bands ON bands.bandID = shows.bandID "
+ "ORDER BY " + orderBy + " LIMIT " + offset + "," + limit;
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
// Uses column-name to avoid confusion when queries are joined
int showID = rs.getInt("showID");
int bandID = rs.getInt("bandID");
String bandName = rs.getString("bandName");
Date date = rs.getDate("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(date);
int state = rs.getInt("state");
String comments = rs.getString("comments");
Date lastEdit = rs.getDate("lastEdit");
SimpleDateFormat lastEditFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
String lastEditString = lastEditFormat.format(lastEdit);
// Handles shows with no Venues
if (rs.getString("venueName") == null) {
results.put(showID, new Show(showID,
new Band(bandID, bandName), dateString, state, comments,
lastEditString));
// Handles shows with Venues
} else {
// Handles shows with one or more venues
if (results.containsKey(showID)) {
// Creates temp array to hold existing venues
Venue[] temp = results.get(showID).getVenues();
// Creates new array, 1 longer than temp
Venue[] newTemp = new Venue[temp.length + 1];
// Inserts new Venue on index 0 (always same place no matter how many venues in current show
newTemp[0] = new Venue(rs.getInt("venueID"),
rs.getString("venueName"));
// Moves the old venues one place up
for (int i = 1; i <= newTemp.length; i++) {
newTemp[i] = temp[i - 1];
}
results.get(showID).setVenues(newTemp);
} else {
// Handles new shows
Venue[] venues = new Venue[1];
venues[0] = new Venue(rs.getInt("venueID"), rs.getString("venueName"));
log.info("Adding new venue, " + venues[0].toString());
results.put(
showID,
new Show(showID, new Band(bandID, bandName), dateString,
state, comments, lastEditString, venues));
}
}
}
rs.close();
log.info("returning " + results.size() + "shows");
return results.values().toArray(new Show[results.size()]);
}
| public static Show[] getShows(int offset, int limit, String orderBy)
throws SQLException {
Connection con = DBConnector.getInstance().getConnection();
HashMap<Integer, Show> results = new HashMap<Integer, Show>();
Statement s = con.createStatement();
String sql = "SELECT shows.*, venues.*, bands.bandID, bands.bandName "
+ "FROM ((shows LEFT OUTER JOIN showvenues ON shows.showID = showvenues.showID) "
+ "LEFT OUTER JOIN venues ON showvenues.venueID = venues.venueID) "
+ "JOIN bands ON bands.bandID = shows.bandID "
+ "ORDER BY " + orderBy + " LIMIT " + offset + "," + limit;
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
// Uses column-name to avoid confusion when queries are joined
int showID = rs.getInt("showID");
int bandID = rs.getInt("bandID");
String bandName = rs.getString("bandName");
Date date = rs.getDate("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(date);
int state = rs.getInt("state");
String comments = rs.getString("comments");
Date lastEdit = rs.getDate("lastEdit");
SimpleDateFormat lastEditFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
String lastEditString = lastEditFormat.format(lastEdit);
// Handles shows with no Venues
if (rs.getString("venueName") == null) {
results.put(showID, new Show(showID,
new Band(bandID, bandName), dateString, state, comments,
lastEditString));
// Handles shows with Venues
} else {
// Handles shows with one or more venues
if (results.containsKey(showID)) {
// Creates temp array to hold existing venues
Venue[] temp = results.get(showID).getVenues();
// Creates new array, 1 longer than temp
Venue[] newTemp = new Venue[temp.length + 1];
// Inserts new Venue on index 0 (always same place no matter how many venues in current show
newTemp[0] = new Venue(rs.getInt("venueID"),
rs.getString("venueName"));
// Moves the old venues one place up
for (int i = 1; i < newTemp.length; i++) {
newTemp[i] = temp[i - 1];
}
results.get(showID).setVenues(newTemp);
} else {
// Handles new shows
Venue[] venues = new Venue[1];
venues[0] = new Venue(rs.getInt("venueID"), rs.getString("venueName"));
log.info("Adding new venue, " + venues[0].toString());
Show newShow = new Show(showID, new Band(bandID, bandName), dateString,
state, comments, lastEditString, venues);
results.put(showID, newShow);
}
}
}
rs.close();
log.info("returning " + results.size() + "shows");
return results.values().toArray(new Show[results.size()]);
}
|
diff --git a/src/com/jgaap/JGAAP.java b/src/com/jgaap/JGAAP.java
index 806435a..051f1d8 100644
--- a/src/com/jgaap/JGAAP.java
+++ b/src/com/jgaap/JGAAP.java
@@ -1,75 +1,75 @@
/*
* JGAAP -- a graphical program for stylometric authorship attribution
* Copyright (C) 2009,2011 by Patrick Juola
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
**/
package com.jgaap;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.jgaap.backend.CLI;
import com.jgaap.ui.JGAAP_UI_MainForm;
/**
* The jgaap main file.
*
* @author michael ryan
*/
public class JGAAP {
static Logger logger = Logger.getLogger("com.jgaap");
static Logger mainLogger = Logger.getLogger(JGAAP.class);
public static boolean commandline = false;
/**
* Launches the jgaap GUI.
*/
private static void createAndShowGUI() {
JGAAP_UI_MainForm gui = new JGAAP_UI_MainForm();
gui.setVisible(true);
}
/**
* launches either the CLI or the GUI based on the command line arguments
* @param args the command line arguments
*/
public static void main(String[] args) {
BasicConfigurator.configure();
- logger.setLevel(Level.ERROR);
+ logger.setLevel(Level.INFO);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
try {
CLI.main(args);
} catch (Exception e) {
mainLogger.fatal("Command Line Failure", e);
}
}
}
}
| true | true | public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.ERROR);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
try {
CLI.main(args);
} catch (Exception e) {
mainLogger.fatal("Command Line Failure", e);
}
}
}
| public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.INFO);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
try {
CLI.main(args);
} catch (Exception e) {
mainLogger.fatal("Command Line Failure", e);
}
}
}
|
diff --git a/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/FreetextQuestionView.java b/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/FreetextQuestionView.java
index 84a89c181..56ed924bc 100644
--- a/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/FreetextQuestionView.java
+++ b/WFPMapping/device/survey/src/com/gallatinsystems/survey/device/view/FreetextQuestionView.java
@@ -1,187 +1,188 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.survey.device.view;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TextView;
import com.gallatinsystems.survey.device.R;
import com.gallatinsystems.survey.device.domain.Question;
import com.gallatinsystems.survey.device.domain.QuestionResponse;
import com.gallatinsystems.survey.device.domain.ValidationRule;
import com.gallatinsystems.survey.device.exception.ValidationException;
import com.gallatinsystems.survey.device.util.ConstantUtil;
/**
* Question that supports free-text input via the keyboard
*
*
* @author Christopher Fagiani
*
*/
public class FreetextQuestionView extends QuestionView implements
OnFocusChangeListener {
private EditText freetextEdit;
public FreetextQuestionView(Context context, Question q,
String defaultLang, String[] langCodes, boolean readOnly) {
super(context, q, defaultLang, langCodes, readOnly);
init();
}
protected void init() {
Context context = getContext();
TableRow tr = new TableRow(context);
freetextEdit = new EditText(context);
freetextEdit.setWidth(DEFAULT_WIDTH);
freetextEdit.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
if (readOnly) {
freetextEdit.setFocusable(false);
}
ValidationRule rule = getQuestion().getValidationRule();
if (rule != null) {
// set the maximum length
if (rule.getMaxLength() != null) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(getQuestion()
.getValidationRule().getMaxLength());
freetextEdit.setFilters(FilterArray);
}
// if the type is numeric, add numeric-specific rules
if (ConstantUtil.NUMERIC_VALIDATION_TYPE.equalsIgnoreCase(rule
.getValidationType())) {
DigitsKeyListener MyDigitKeyListener = new DigitsKeyListener(
rule.getAllowSigned(), rule.getAllowDecimal());
freetextEdit.setKeyListener(MyDigitKeyListener);
}
}
freetextEdit.setOnFocusChangeListener(this);
freetextEdit.setWidth(screenWidth - 50);
tr.addView(freetextEdit);
addView(tr);
}
/**
* pulls the data out of the fields and saves it as a response object
*/
@Override
public void captureResponse() {
captureResponse(false);
}
@Override
public void setResponse(QuestionResponse resp) {
if (resp != null && freetextEdit != null) {
freetextEdit.setText(resp.getValue());
}
super.setResponse(resp);
}
/**
* pulls the data out of the fields and saves it as a response object,
* possibly suppressing listeners
*/
public void captureResponse(boolean suppressListeners) {
setResponse(new QuestionResponse(freetextEdit.getText().toString(),
ConstantUtil.VALUE_RESPONSE_TYPE, getQuestion().getId()),
suppressListeners);
}
@Override
public void rehydrate(QuestionResponse resp) {
super.rehydrate(resp);
if (resp != null) {
freetextEdit.setText(resp.getValue());
}
}
@Override
public void resetQuestion(boolean fireEvent) {
super.resetQuestion(fireEvent);
freetextEdit.setText("");
}
/**
* captures the response and runs validation on loss of focus
*/
@Override
public void onFocusChange(View view, boolean hasFocus) {
// we need to listen to loss of focus
// and make sure input is valid
if (!hasFocus) {
ValidationRule currentRule = getQuestion().getValidationRule();
EditText textEdit = (EditText) view;
if (textEdit.getText() != null
&& textEdit.getText().toString().trim().length() > 0) {
if (currentRule != null) {
try {
String validatedText = currentRule
.performValidation(textEdit.getText()
.toString());
textEdit.setText(validatedText);
// now capture the response
captureResponse();
} catch (ValidationException e) {
// if we failed validation, display
// a message to the user
AlertDialog.Builder builder = new AlertDialog.Builder(
getContext());
builder.setTitle(R.string.validationerrtitle);
TextView tipText = new TextView(getContext());
if (ValidationException.TOO_LARGE.equals(e.getType())) {
String baseText = getResources().getString(
R.string.toolargeerr);
tipText.setText(baseText
+ currentRule.getMaxValString());
} else if (ValidationException.TOO_SMALL.equals(e
.getType())) {
String baseText = getResources().getString(
R.string.toosmallerr);
tipText.setText(baseText
+ currentRule.getMinValString());
} else {
tipText.setText(R.string.baddatatypeerr);
}
builder.setView(tipText);
builder.setPositiveButton(R.string.okbutton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if(dialog!=null){
dialog.dismiss();
}
}
});
builder.show();
+ resetQuestion(false); //Enforce validation by clearing field
}
} else {
captureResponse();
}
}
}
}
}
| true | true | public void onFocusChange(View view, boolean hasFocus) {
// we need to listen to loss of focus
// and make sure input is valid
if (!hasFocus) {
ValidationRule currentRule = getQuestion().getValidationRule();
EditText textEdit = (EditText) view;
if (textEdit.getText() != null
&& textEdit.getText().toString().trim().length() > 0) {
if (currentRule != null) {
try {
String validatedText = currentRule
.performValidation(textEdit.getText()
.toString());
textEdit.setText(validatedText);
// now capture the response
captureResponse();
} catch (ValidationException e) {
// if we failed validation, display
// a message to the user
AlertDialog.Builder builder = new AlertDialog.Builder(
getContext());
builder.setTitle(R.string.validationerrtitle);
TextView tipText = new TextView(getContext());
if (ValidationException.TOO_LARGE.equals(e.getType())) {
String baseText = getResources().getString(
R.string.toolargeerr);
tipText.setText(baseText
+ currentRule.getMaxValString());
} else if (ValidationException.TOO_SMALL.equals(e
.getType())) {
String baseText = getResources().getString(
R.string.toosmallerr);
tipText.setText(baseText
+ currentRule.getMinValString());
} else {
tipText.setText(R.string.baddatatypeerr);
}
builder.setView(tipText);
builder.setPositiveButton(R.string.okbutton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if(dialog!=null){
dialog.dismiss();
}
}
});
builder.show();
}
} else {
captureResponse();
}
}
}
}
| public void onFocusChange(View view, boolean hasFocus) {
// we need to listen to loss of focus
// and make sure input is valid
if (!hasFocus) {
ValidationRule currentRule = getQuestion().getValidationRule();
EditText textEdit = (EditText) view;
if (textEdit.getText() != null
&& textEdit.getText().toString().trim().length() > 0) {
if (currentRule != null) {
try {
String validatedText = currentRule
.performValidation(textEdit.getText()
.toString());
textEdit.setText(validatedText);
// now capture the response
captureResponse();
} catch (ValidationException e) {
// if we failed validation, display
// a message to the user
AlertDialog.Builder builder = new AlertDialog.Builder(
getContext());
builder.setTitle(R.string.validationerrtitle);
TextView tipText = new TextView(getContext());
if (ValidationException.TOO_LARGE.equals(e.getType())) {
String baseText = getResources().getString(
R.string.toolargeerr);
tipText.setText(baseText
+ currentRule.getMaxValString());
} else if (ValidationException.TOO_SMALL.equals(e
.getType())) {
String baseText = getResources().getString(
R.string.toosmallerr);
tipText.setText(baseText
+ currentRule.getMinValString());
} else {
tipText.setText(R.string.baddatatypeerr);
}
builder.setView(tipText);
builder.setPositiveButton(R.string.okbutton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if(dialog!=null){
dialog.dismiss();
}
}
});
builder.show();
resetQuestion(false); //Enforce validation by clearing field
}
} else {
captureResponse();
}
}
}
}
|
diff --git a/src/scripts/clusterManipulations/SplitFasta.java b/src/scripts/clusterManipulations/SplitFasta.java
index a526fdd0..63850ad3 100644
--- a/src/scripts/clusterManipulations/SplitFasta.java
+++ b/src/scripts/clusterManipulations/SplitFasta.java
@@ -1,63 +1,63 @@
/**
* Author: [email protected]
* This code 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,
* provided that any use properly credits the author.
* 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 at http://www.gnu.org * * */
package scripts.clusterManipulations;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import parsers.FastaSequence;
import parsers.FastaSequenceOneAtATime;
public class SplitFasta
{
public static void main(String[] args) throws Exception
{
- if( args.length != 1)
+ if( args.length != 2)
{
System.out.println("Usage SplitFasta fileToSplit numSequencesPerSplit");
System.exit(1);
}
FastaSequenceOneAtATime fsoat = new FastaSequenceOneAtATime(args[0]);
int splitSize = Integer.parseInt(args[1]);
int count=0;
int file =1;
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
for( FastaSequence fs = fsoat.getNextSequence(); fs != null; fs = fsoat.getNextSequence() )
{
count++;
if( count == splitSize)
{
writer.flush(); writer.close();
count =0;
file++;
writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
System.out.println("Finished " + args[0] + "_FILE_" + file);
}
writer.write(fs.getHeader() + "\n");
writer.write(fs.getSequence() + "\n");
}
System.out.println("Finished");
writer.flush(); writer.close();
}
}
| true | true | public static void main(String[] args) throws Exception
{
if( args.length != 1)
{
System.out.println("Usage SplitFasta fileToSplit numSequencesPerSplit");
System.exit(1);
}
FastaSequenceOneAtATime fsoat = new FastaSequenceOneAtATime(args[0]);
int splitSize = Integer.parseInt(args[1]);
int count=0;
int file =1;
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
for( FastaSequence fs = fsoat.getNextSequence(); fs != null; fs = fsoat.getNextSequence() )
{
count++;
if( count == splitSize)
{
writer.flush(); writer.close();
count =0;
file++;
writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
System.out.println("Finished " + args[0] + "_FILE_" + file);
}
writer.write(fs.getHeader() + "\n");
writer.write(fs.getSequence() + "\n");
}
System.out.println("Finished");
writer.flush(); writer.close();
}
| public static void main(String[] args) throws Exception
{
if( args.length != 2)
{
System.out.println("Usage SplitFasta fileToSplit numSequencesPerSplit");
System.exit(1);
}
FastaSequenceOneAtATime fsoat = new FastaSequenceOneAtATime(args[0]);
int splitSize = Integer.parseInt(args[1]);
int count=0;
int file =1;
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
for( FastaSequence fs = fsoat.getNextSequence(); fs != null; fs = fsoat.getNextSequence() )
{
count++;
if( count == splitSize)
{
writer.flush(); writer.close();
count =0;
file++;
writer = new BufferedWriter(new FileWriter(new File(args[0] + "_FILE_" + file)));
System.out.println("Finished " + args[0] + "_FILE_" + file);
}
writer.write(fs.getHeader() + "\n");
writer.write(fs.getSequence() + "\n");
}
System.out.println("Finished");
writer.flush(); writer.close();
}
|
diff --git a/ActiveObjects/src/net/java/ao/EntityManager.java b/ActiveObjects/src/net/java/ao/EntityManager.java
index 86084e2..40ed991 100644
--- a/ActiveObjects/src/net/java/ao/EntityManager.java
+++ b/ActiveObjects/src/net/java/ao/EntityManager.java
@@ -1,1152 +1,1152 @@
/*
* Copyright 2007 Daniel Spiewak
*
* 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 net.java.ao;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
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.WeakHashMap;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.java.ao.cache.Cache;
import net.java.ao.cache.CacheLayer;
import net.java.ao.cache.RAMCache;
import net.java.ao.cache.RAMRelationsCache;
import net.java.ao.cache.RelationsCache;
import net.java.ao.schema.AutoIncrement;
import net.java.ao.schema.CamelCaseFieldNameConverter;
import net.java.ao.schema.CamelCaseTableNameConverter;
import net.java.ao.schema.FieldNameConverter;
import net.java.ao.schema.SchemaGenerator;
import net.java.ao.schema.TableNameConverter;
import net.java.ao.types.DatabaseType;
import net.java.ao.types.TypeManager;
/**
* <p>The root control class for the entire ActiveObjects API. <code>EntityManager</code>
* is the source of all {@link RawEntity} objects, as well as the dispatch layer between the entities,
* the pluggable table name converters, and the database abstraction layers. This is the
* entry point for any use of the API.</p>
*
* <p><code>EntityManager</code> is designed to be used in an instance fashion with each
* instance corresponding to a single database. Thus, rather than a singleton instance or a
* static factory method, <code>EntityManager</code> does have a proper constructor. Any
* static instance management is left up to the developer using the API.</p>
*
* <p>As a side note, ActiveObjects can optionally log all SQL queries prior to their
* execution. This query logging is done with the Java Logging API using the {@link Logger}
* instance for the <code>net.java.ao</code> package. This logging is disabled by default
* by the <code>EntityManager</code> static initializer. Thus, if it is desirable to log the
* SQL statements, the <code>Logger</code> level must be set to {@link Level.FINE}
* <i>after</i> the <code>EntityManager</code> class is first used. This usually means
* setting the log level after the constructer has been called.</p>
*
* @author Daniel Spiewak
*/
public class EntityManager {
static {
Logger.getLogger("net.java.ao").setLevel(Level.OFF);
}
private final DatabaseProvider provider;
private final boolean weaklyCache;
private Map<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>> proxies;
private final ReadWriteLock proxyLock = new ReentrantReadWriteLock(true);
private Map<CacheKey<?>, Reference<RawEntity<?>>> entityCache;
private final ReadWriteLock entityCacheLock = new ReentrantReadWriteLock(true);
private Cache cache;
private final ReadWriteLock cacheLock = new ReentrantReadWriteLock(true);
private TableNameConverter tableNameConverter;
private final ReadWriteLock tableNameConverterLock = new ReentrantReadWriteLock(true);
private FieldNameConverter fieldNameConverter;
private final ReadWriteLock fieldNameConverterLock = new ReentrantReadWriteLock(true);
private PolymorphicTypeMapper typeMapper;
private final ReadWriteLock typeMapperLock = new ReentrantReadWriteLock(true);
private Map<Class<? extends ValueGenerator<?>>, ValueGenerator<?>> valGenCache;
private final ReadWriteLock valGenCacheLock = new ReentrantReadWriteLock(true);
private final RelationsCache relationsCache = new RAMRelationsCache();
/**
* Creates a new instance of <code>EntityManager</code> using the specified
* {@link DatabaseProvider}. This constructor intializes the entity cache, as well
* as creates the default {@link TableNameConverter} (the default is
* {@link CamelCaseTableNameConverter}, which is non-pluralized) and the default
* {@link FieldNameConverter} ({@link CamelCaseFieldNameConverter}). The provider
* instance is immutable once set using this constructor. By default (using this
* constructor), all entities are strongly cached, meaning references are held to
* the instances, preventing garbage collection.
*
* @param provider The {@link DatabaseProvider} to use in all database operations.
* @see #EntityManager(DatabaseProvider, boolean)
*/
public EntityManager(DatabaseProvider provider) {
this(provider, false);
}
/**
* Creates a new instance of <code>EntityManager</code> using the specified
* {@link DatabaseProvider}. This constructor initializes the entity and proxy
* caches based on the given boolean value. If <code>true</code>, the entities
* will be weakly cached, not maintaining a reference allowing for garbage
* collection. If <code>false</code>, then strong caching will be used, preventing
* garbage collection and ensuring the cache is logically complete. If you are
* concerned about memory, specify <code>true</code>. Otherwise, for
* maximum performance use <code>false</code> (highly recomended).
*
* @param provider The {@link DatabaseProvider} to use in all database operations.
* @param weaklyCache Whether or not to use {@link WeakReference} in the entity
* cache. If <code>false</code>, then {@link SoftReference} will be used.
*/
public EntityManager(DatabaseProvider provider, boolean weaklyCache) {
this.provider = provider;
this.weaklyCache = weaklyCache;
if (weaklyCache) {
proxies = new WeakHashMap<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>();
} else {
proxies = new SoftHashMap<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>();
}
entityCache = new HashMap<CacheKey<?>, Reference<RawEntity<?>>>();
cache = new RAMCache();
valGenCache = new HashMap<Class<? extends ValueGenerator<?>>, ValueGenerator<?>>();
tableNameConverter = new CamelCaseTableNameConverter();
fieldNameConverter = new CamelCaseFieldNameConverter();
typeMapper = new DefaultPolymorphicTypeMapper(new HashMap<Class<? extends RawEntity<?>>, String>());
}
/**
* <p>Creates a new instance of <code>EntityManager</code> by auto-magically
* finding a {@link DatabaseProvider} instance for the specified JDBC URI, username
* and password. The auto-magically determined instance is pooled by default
* (if a supported connection pooling library is available on the classpath).</p>
*
* <p>The actual auto-magical parsing code isn't contained within this method,
* but in {@link DatabaseProvider#getInstance(String, String, String)}. This way,
* it is possible to use the parsing logic to get a <code>DatabaseProvider</code>
* instance separate from <code>EntityManager</code> if necessary.</p>
*
* @param uri The JDBC URI to use for the database connection.
* @param username The username to use in authenticating the database connection.
* @param password The password to use in authenticating the database connection.
* @see #EntityManager(DatabaseProvider)
* @see net.java.ao.DatabaseProvider#getInstance(String, String, String)
*/
public EntityManager(String uri, String username, String password) {
this(DatabaseProvider.getInstance(uri, username, password));
}
/**
* Convenience method to create the schema for the specified entities
* using the current settings (table/field name converter and database provider).
*
* @see net.java.ao.schema.SchemaGenerator#migrate(DatabaseProvider, TableNameConverter, FieldNameConverter, Class...)
*/
public void migrate(Class<? extends RawEntity<?>>... entities) throws SQLException {
tableNameConverterLock.readLock().lock();
fieldNameConverterLock.readLock().lock();
try {
SchemaGenerator.migrate(provider, tableNameConverter, fieldNameConverter, entities);
} finally {
fieldNameConverterLock.readLock().unlock();
tableNameConverterLock.readLock().unlock();
}
}
/**
* Flushes all value caches contained within entities controlled by this <code>EntityManager</code>
* instance. This does not actually remove the entities from the instance cache maintained
* within this class. Rather, it simply dumps all of the field values cached within the entities
* themselves (with the exception of the primary key value). This should be used in the case
* of a complex process outside AO control which may have changed values in the database. If
* it is at all possible to determine precisely which rows have been changed, the {@link #flush(RawEntity...)}
* method should be used instead.
*/
public void flushAll() {
List<Map.Entry<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>> toFlush = new LinkedList<Map.Entry<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>>();
proxyLock.readLock().lock();
try {
for (Map.Entry<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>> proxy : proxies.entrySet()) {
toFlush.add(proxy);
}
} finally {
proxyLock.readLock().unlock();
}
for (Map.Entry<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>> entry : toFlush) {
entry.getValue().flushCache(entry.getKey());
}
relationsCache.flush();
}
/**
* Flushes the value caches of the specified entities along with all of the relevant
* relations cache entries. This should be called after a process outside of AO control
* may have modified the values in the specified rows. This does not actually remove
* the entity instances themselves from the instance cache. Rather, it just flushes all
* of their internally cached values (with the exception of the primary key).
*/
public void flush(RawEntity<?>... entities) {
List<Class<? extends RawEntity<?>>> types = new ArrayList<Class<? extends RawEntity<?>>>(entities.length);
Map<RawEntity<?>, EntityProxy<?, ?>> toFlush = new HashMap<RawEntity<?>, EntityProxy<?, ?>>();
proxyLock.readLock().lock();
try {
for (RawEntity<?> entity : entities) {
verify(entity);
types.add(entity.getEntityType());
toFlush.put(entity, proxies.get(entity));
}
} finally {
proxyLock.readLock().unlock();
}
for (Entry<RawEntity<?>, EntityProxy<?, ?>> entry : toFlush.entrySet()) {
entry.getValue().flushCache(entry.getKey());
}
relationsCache.remove(types.toArray(new Class[types.size()]));
}
/**
* <p>Returns an array of entities of the specified type corresponding to the
* varargs primary keys. If an in-memory reference already exists to a corresponding
* entity (of the specified type and key), it is returned rather than creating
* a new instance.</p>
*
* <p>If the entity is known to exist in the database, then no checks are performed
* and the method returns extremely quickly. However, for any key which has not
* already been verified, a query to the database is performed to determine whether
* or not the entity exists. If the entity does not exist, then <code>null</code>
* is returned.</p>
*
* @param type The type of the entities to retrieve.
* @param keys The primary keys corresponding to the entities to retrieve. All
* keys must be typed according to the generic type parameter of the entity's
* {@link RawEntity} inheritence (if inheriting from {@link Entity}, this is <code>Integer</code>
* or <code>int</code>). Thus, the <code>keys</code> array is type-checked at compile
* time.
* @return An array of entities of the given type corresponding with the specified
* primary keys. Any entities which are non-existent will correspond to a <code>null</code>
* value in the resulting array.
*/
public <T extends RawEntity<K>, K> T[] get(final Class<T> type, K... keys) {
final String primaryKeyField = Common.getPrimaryKeyField(type, getFieldNameConverter());
final String tableName = getTableNameConverter().getName(type);
return getFromCache(type, new Function<T, K>() {
public T invoke(K key) {
T back = null;
Connection conn = null;
try {
DatabaseProvider provider = getProvider();
conn = provider.getConnection();
StringBuilder sql = new StringBuilder("SELECT ");
sql.append(provider.processID(primaryKeyField));
sql.append(" FROM ").append(provider.processID(tableName));
sql.append(" WHERE ").append(provider.processID(primaryKeyField));
sql.append(" = ?");
PreparedStatement stmt = conn.prepareStatement(sql.toString());
DatabaseType<K> dbType = (DatabaseType<K>) TypeManager.getInstance().getType(key.getClass());
dbType.putToDatabase(EntityManager.this, stmt, 1, key);
ResultSet res = stmt.executeQuery();
if (res.next()) {
back = getAndInstantiate(type, key);
}
res.close();
stmt.close();
} catch (SQLException e) {
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
return back;
}
}, keys);
}
protected <T extends RawEntity<K>, K> T[] peer(final Class<T> type, K... keys) {
return getFromCache(type, new Function<T, K>() {
public T invoke(K key) {
return getAndInstantiate(type, key);
}
}, keys);
}
private <T extends RawEntity<K>, K> T[] getFromCache(Class<T> type, Function<T, K> create, K... keys) {
T[] back = (T[]) Array.newInstance(type, keys.length);
int index = 0;
for (K key : keys) {
entityCacheLock.writeLock().lock();
try { // upcast to workaround bug in javac
Reference<?> reference = entityCache.get(new CacheKey<K>(key, type));
Reference<T> ref = (Reference<T>) reference;
T entity = (ref == null ? null : ref.get());
if (entity != null) {
back[index++] = entity;
} else {
back[index++] = create.invoke(key);
}
} finally {
entityCacheLock.writeLock().unlock();
}
}
return back;
}
/**
* Creates a new instance of the entity of the specified type corresponding to the
* given primary key. This is used by {@link #get(Class, Object...)} to create the entity
* if the instance is not found already in the cache. This method should not be
* repurposed to perform any caching, since ActiveObjects already assumes that
* the caching has been performed.
*
* @param type The type of the entity to create.
* @param key The primary key corresponding to the entity instance required.
* @return An entity instance of the specified type and primary key.
*/
protected <T extends RawEntity<K>, K> T getAndInstantiate(Class<T> type, K key) {
EntityProxy<T, K> proxy = new EntityProxy<T, K>(this, type, key);
T entity = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, proxy);
proxyLock.writeLock().lock();
try {
proxies.put(entity, proxy);
} finally {
proxyLock.writeLock().unlock();
}
entityCache.put(new CacheKey<K>(key, type), createRef(entity));
return entity;
}
/**
* Cleverly overloaded method to return a single entity of the specified type
* rather than an array in the case where only one ID is passed. This method
* meerly delegates the call to the overloaded <code>get</code> method
* and functions as syntactical sugar.
*
* @param type The type of the entity instance to retrieve.
* @param key The primary key corresponding to the entity to be retrieved.
* @return An entity instance of the given type corresponding to the specified
* primary key, or <code>null</code> if the entity does not exist in the database.
* @see #get(Class, Object...)
*/
public <T extends RawEntity<K>, K> T get(Class<T> type, K key) {
return get(type, (K[]) new Object[] {key})[0];
}
protected <T extends RawEntity<K>, K> T peer(Class<T> type, K key) {
return peer(type, (K[]) new Object[] {key})[0];
}
/**
* <p>Creates a new entity of the specified type with the optionally specified
* initial parameters. This method actually inserts a row into the table represented
* by the entity type and returns the entity instance which corresponds to that
* row.</p>
*
* <p>The {@link DBParam} object parameters are designed to allow the creation
* of entities which have non-null fields which have no defalut or auto-generated
* value. Insertion of a row without such field values would of course fail,
* thus the need for db params. The db params can also be used to set
* the values for any field in the row, leading to more compact code under
* certain circumstances.</p>
*
* <p>Unless within a transaction, this method will commit to the database
* immediately and exactly once per call. Thus, care should be taken in
* the creation of large numbers of entities. There doesn't seem to be a more
* efficient way to create large numbers of entities, however one should still
* be aware of the performance implications.</p>
*
* <p>This method delegates the action INSERT action to
* {@link DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String, boolean, String, DBParam...)}.
* This is necessary because not all databases support the JDBC <code>RETURN_GENERATED_KEYS</code>
* constant (e.g. PostgreSQL and HSQLDB). Thus, the database provider itself is
* responsible for handling INSERTion and retrieval of the correct primary key
* value.</p>
*
* @param type The type of the entity to INSERT.
* @param params An optional varargs array of initial values for the fields in the row. These
* values will be passed to the database within the INSERT statement.
* @return The new entity instance corresponding to the INSERTed row.
* @see net.java.ao.DBParam
* @see net.java.ao.DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String, boolean, String, DBParam...)
*/
public <T extends RawEntity<K>, K> T create(Class<T> type, DBParam... params) throws SQLException {
T back = null;
String table = null;
tableNameConverterLock.readLock().lock();
try {
table = tableNameConverter.getName(type);
} finally {
tableNameConverterLock.readLock().unlock();
}
Set<DBParam> listParams = new HashSet<DBParam>();
listParams.addAll(Arrays.asList(params));
fieldNameConverterLock.readLock().lock();
try {
for (Method method : MethodFinder.getInstance().findAnnotation(Generator.class, type)) {
Generator genAnno = method.getAnnotation(Generator.class);
String field = fieldNameConverter.getName(method);
ValueGenerator<?> generator;
valGenCacheLock.writeLock().lock();
try {
if (valGenCache.containsKey(genAnno.value())) {
generator = valGenCache.get(genAnno.value());
} else {
generator = genAnno.value().newInstance();
valGenCache.put(genAnno.value(), generator);
}
} catch (InstantiationException e) {
continue;
} catch (IllegalAccessException e) {
continue;
} finally {
valGenCacheLock.writeLock().unlock();
}
listParams.add(new DBParam(field, generator.generateValue(this)));
}
// <ian>
Version version = type.getAnnotation(Version.class);
if (version != null) {
// Initialize version upon creation.
String field = version.value();
int initial = version.initial();
listParams.add(new DBParam(field, initial));
}
// </ian>
} finally {
fieldNameConverterLock.readLock().unlock();
}
Connection conn = getProvider().getConnection();
try {
Method pkMethod = Common.getPrimaryKeyMethod(type);
back = peer(type, provider.insertReturningKey(this, conn,
Common.getPrimaryKeyClassType(type),
Common.getPrimaryKeyField(type, getFieldNameConverter()),
pkMethod.getAnnotation(AutoIncrement.class) != null, table, listParams.toArray(new DBParam[listParams.size()])));
} finally {
conn.close();
}
relationsCache.remove(type);
back.init();
return back;
}
/**
* Creates and INSERTs a new entity of the specified type with the given map of
* parameters. This method merely delegates to the {@link #create(Class, DBParam...)}
* method. The idea behind having a separate convenience method taking a map is in
* circumstances with large numbers of parameters or for people familiar with the
* anonymous inner class constructor syntax who might be more comfortable with
* creating a map than with passing a number of objects.
*
* @param type The type of the entity to INSERT.
* @param params A map of parameters to pass to the INSERT.
* @return The new entity instance corresponding to the INSERTed row.
* @see #create(Class, DBParam...)
*/
public <T extends RawEntity<K>, K> T create(Class<T> type, Map<String, Object> params) throws SQLException {
DBParam[] arrParams = new DBParam[params.size()];
int i = 0;
for (String key : params.keySet()) {
arrParams[i++] = new DBParam(key, params.get(key));
}
return create(type, arrParams);
}
/**
* <p>Deletes the specified entities from the database. DELETE statements are
* called on the rows in the corresponding tables and the entities are removed
* from the instance cache. The entity instances themselves are not invalidated,
* but it doesn't even make sense to continue using the instance without a row
* with which it is paired.</p>
*
* <p>This method does attempt to group the DELETE statements on a per-type
* basis. Thus, if you pass 5 instances of <code>EntityA</code> and two
* instances of <code>EntityB</code>, the following SQL prepared statements
* will be invoked:</p>
*
* <pre>DELETE FROM entityA WHERE id IN (?,?,?,?,?);
* DELETE FROM entityB WHERE id IN (?,?);</pre>
*
* <p>Thus, this method scales very well for large numbers of entities grouped
* into types. However, the execution time increases linearly for each entity of
* unique type.</p>
*
* @param entities A varargs array of entities to delete. Method returns immediately
* if length == 0.
*/
@SuppressWarnings("unchecked")
public void delete(RawEntity<?>... entities) throws SQLException {
if (entities.length == 0) {
return;
}
Map<Class<? extends RawEntity<?>>, List<RawEntity<?>>> organizedEntities =
new HashMap<Class<? extends RawEntity<?>>, List<RawEntity<?>>>();
for (RawEntity<?> entity : entities) {
verify(entity);
Class<? extends RawEntity<?>> type = getProxyForEntity(entity).getType();
if (!organizedEntities.containsKey(type)) {
organizedEntities.put(type, new LinkedList<RawEntity<?>>());
}
organizedEntities.get(type).add(entity);
}
entityCacheLock.writeLock().lock();
try {
DatabaseProvider provider = getProvider();
Connection conn = provider.getConnection();
try {
for (Class<? extends RawEntity<?>> type : organizedEntities.keySet()) {
List<RawEntity<?>> entityList = organizedEntities.get(type);
StringBuilder sql = new StringBuilder("DELETE FROM ");
tableNameConverterLock.readLock().lock();
try {
sql.append(provider.processID(tableNameConverter.getName(type)));
} finally {
tableNameConverterLock.readLock().unlock();
}
sql.append(" WHERE ").append(provider.processID(
Common.getPrimaryKeyField(type, getFieldNameConverter()))).append(" IN (?");
for (int i = 1; i < entityList.size(); i++) {
sql.append(",?");
}
sql.append(')');
Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
int index = 1;
for (RawEntity<?> entity : entityList) {
TypeManager.getInstance().getType((Class) entity.getEntityType()).putToDatabase(this, stmt, index++, entity);
}
relationsCache.remove(type);
stmt.executeUpdate();
stmt.close();
}
} finally {
conn.close();
}
for (RawEntity<?> entity : entities) {
entityCache.remove(new CacheKey(Common.getPrimaryKeyValue(entity), entity.getEntityType()));
}
proxyLock.writeLock().lock();
try {
for (RawEntity<?> entity : entities) {
proxies.remove(entity);
}
} finally {
proxyLock.writeLock().unlock();
}
} finally {
entityCacheLock.writeLock().unlock();
}
}
/**
* Returns all entities of the given type. This actually peers the call to
* the {@link #find(Class, Query)} method.
*
* @param type The type of entity to retrieve.
* @return An array of all entities which correspond to the given type.
*/
public <T extends RawEntity<K>, K> T[] find(Class<T> type) throws SQLException {
return find(type, Query.select());
}
/**
* <p>Convenience method to select all entities of the given type with the
* specified, parameterized criteria. The <code>criteria</code> String
* specified is appended to the SQL prepared statement immediately
* following the <code>WHERE</code>.</p>
*
* <p>Example:</p>
*
* <pre>manager.find(Person.class, "name LIKE ? OR age > ?", "Joe", 9);</pre>
*
* <p>This actually delegates the call to the {@link #find(Class, Query)}
* method, properly parameterizing the {@link Query} object.</p>
*
* @param type The type of the entities to retrieve.
* @param criteria A parameterized WHERE statement used to determine the results.
* @param parameters A varargs array of parameters to be passed to the executed
* prepared statement. The length of this array <i>must</i> match the number of
* parameters (denoted by the '?' char) in the <code>criteria</code>.
* @return An array of entities of the given type which match the specified criteria.
*/
public <T extends RawEntity<K>, K> T[] find(Class<T> type, String criteria, Object... parameters) throws SQLException {
return find(type, Query.select().where(criteria, parameters));
}
/**
* <p>Selects all entities matching the given type and {@link Query}. By default, the
* entities will be created based on the values within the primary key field for the
* specified type (this is usually the desired behavior).</p>
*
* <p>Example:</p>
*
* <pre>manager.find(Person.class, Query.select().where("name LIKE ? OR age > ?", "Joe", 9).limit(10));</pre>
*
* <p>This method delegates the call to {@link #find(Class, String, Query)}, passing the
* primary key field for the given type as the <code>String</code> parameter.</p>
*
* @param type The type of the entities to retrieve.
* @param query The {@link Query} instance to be used to determine the results.
* @return An array of entities of the given type which match the specified query.
*/
public <T extends RawEntity<K>, K> T[] find(Class<T> type, Query query) throws SQLException {
String selectField = Common.getPrimaryKeyField(type, getFieldNameConverter());
query.resolveFields(type, getFieldNameConverter());
String[] fields = query.getFields();
if (fields.length == 1) {
selectField = fields[0];
}
return find(type, selectField, query);
}
/**
* <p>Selects all entities of the specified type which match the given
* <code>Query</code>. This method creates a <code>PreparedStatement</code>
* using the <code>Query</code> instance specified against the table
* represented by the given type. This query is then executed (with the
* parameters specified in the query). The method then iterates through
* the result set and extracts the specified field, mapping an entity
* of the given type to each row. This array of entities is returned.</p>
*
* @param type The type of the entities to retrieve.
* @param field The field value to use in the creation of the entities. This is usually
* the primary key field of the corresponding table.
* @param query The {@link Query} instance to use in determining the results.
* @return An array of entities of the given type which match the specified query.
*/
public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException {
List<T> back = new ArrayList<T>();
query.resolveFields(type, getFieldNameConverter());
// <ian>
Version version = type.getAnnotation(Version.class);
- if (version != null && version.findInitial()) {
+ if (version != null && !version.findInitial()) {
// Add initial version check to exclude
// objects that have only been created and not saved yet.
if (query.getWhereClause() == null) {
query.where(version.value() + " != ?", version.initial());
} else {
// Preserve existing WHERE clause and parameters
String whereClause = new StringBuilder().append(query.getWhereClause())
.append(" AND ").append(version.value()).append(" != ?").toString();
Object[] paramsOld = query.getWhereParams();
Object[] paramsNew = new Object[paramsOld.length + 1];
System.arraycopy(paramsOld, 0, paramsNew, 0, paramsOld.length);
paramsNew[paramsNew.length - 1] = version.initial();
query.setWhereClause(whereClause);
query.setWhereParams(paramsNew);
}
}
// </ian>
Preload preloadAnnotation = type.getAnnotation(Preload.class);
if (preloadAnnotation != null) {
if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) {
String[] oldFields = query.getFields();
List<String> newFields = new ArrayList<String>();
for (String newField : preloadAnnotation.value()) {
newField = newField.trim();
int fieldLoc = -1;
for (int i = 0; i < oldFields.length; i++) {
if (oldFields[i].equals(newField)) {
fieldLoc = i;
break;
}
}
if (fieldLoc < 0) {
newFields.add(newField);
} else {
newFields.add(oldFields[fieldLoc]);
}
}
if (!newFields.contains("*")) {
for (String oldField : oldFields) {
if (!newFields.contains(oldField)) {
newFields.add(oldField);
}
}
}
query.setFields(newFields.toArray(new String[newFields.size()]));
}
}
Connection conn = getProvider().getConnection();
try {
String sql = null;
tableNameConverterLock.readLock().lock();
try {
sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false);
} finally {
tableNameConverterLock.readLock().unlock();
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
provider.setQueryStatementProperties(stmt, query);
query.setParameters(this, stmt);
ResultSet res = stmt.executeQuery();
provider.setQueryResultSetProperties(res, query);
while (res.next()) {
T entity = peer(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field));
CacheLayer cacheLayer = getProxyForEntity(entity).getCacheLayer(entity);
for (String cacheField : query.getCanonicalFields(type, fieldNameConverter)) {
cacheLayer.put(cacheField, res.getObject(cacheField));
}
back.add(entity);
}
res.close();
stmt.close();
} finally {
conn.close();
}
return back.toArray((T[]) Array.newInstance(type, back.size()));
}
/**
* <p>Executes the specified SQL and extracts the given key field, wrapping each
* row into a instance of the specified type. The SQL itself is executed as
* a {@link PreparedStatement} with the given parameters.</p>
*
* <p>Example:</p>
*
* <pre>manager.findWithSQL(Person.class, "personID", "SELECT personID FROM chairs WHERE position < ? LIMIT ?", 10, 5);</pre>
*
* <p>The SQL is not parsed or modified in any way by ActiveObjects. As such, it is
* possible to execute database-specific queries using this method without realizing
* it. For example, the above query will not run on MS SQL Server or Oracle, due to
* the lack of a LIMIT clause in their SQL implementation. As such, be extremely
* careful about what SQL is executed using this method, or else be conscious of the
* fact that you may be locking yourself to a specific DBMS.</p>
*
* @param type The type of the entities to retrieve.
* @param keyField The field value to use in the creation of the entities. This is usually
* the primary key field of the corresponding table.
* @param sql The SQL statement to execute.
* @param parameters A varargs array of parameters to be passed to the executed
* prepared statement. The length of this array <i>must</i> match the number of
* parameters (denoted by the '?' char) in the <code>criteria</code>.
* @return An array of entities of the given type which match the specified query.
*/
@SuppressWarnings("unchecked")
public <T extends RawEntity<K>, K> T[] findWithSQL(Class<T> type, String keyField, String sql, Object... parameters) throws SQLException {
List<T> back = new ArrayList<T>();
Connection conn = getProvider().getConnection();
try {
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql);
TypeManager manager = TypeManager.getInstance();
for (int i = 0; i < parameters.length; i++) {
Class javaType = parameters[i].getClass();
if (parameters[i] instanceof RawEntity) {
javaType = ((RawEntity<?>) parameters[i]).getEntityType();
}
manager.getType(javaType).putToDatabase(this, stmt, i + 1, parameters[i]);
}
ResultSet res = stmt.executeQuery();
while (res.next()) {
back.add(peer(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, (Class<? extends K>) type, keyField)));
}
res.close();
stmt.close();
} finally {
conn.close();
}
return back.toArray((T[]) Array.newInstance(type, back.size()));
}
/**
* Counts all entities of the specified type. This method is actually
* a delegate for: <code>count(Class<? extends Entity>, Query)</code>
*
* @param type The type of the entities which should be counted.
* @return The number of entities of the specified type.
*/
public <K> int count(Class<? extends RawEntity<K>> type) throws SQLException {
return count(type, Query.select());
}
/**
* Counts all entities of the specified type matching the given criteria
* and parameters. This is a convenience method for:
* <code>count(type, Query.select().where(criteria, parameters))</code>
*
* @param type The type of the entities which should be counted.
* @param criteria A parameterized WHERE statement used to determine the result
* set which will be counted.
* @param parameters A varargs array of parameters to be passed to the executed
* prepared statement. The length of this array <i>must</i> match the number of
* parameters (denoted by the '?' char) in the <code>criteria</code>.
* @return The number of entities of the given type which match the specified criteria.
*/
public <K> int count(Class<? extends RawEntity<K>> type, String criteria, Object... parameters) throws SQLException {
return count(type, Query.select().where(criteria, parameters));
}
/**
* Counts all entities of the specified type matching the given {@link Query}
* instance. The SQL runs as a <code>SELECT COUNT(*)</code> to
* ensure maximum performance.
*
* @param type The type of the entities which should be counted.
* @param query The {@link Query} instance used to determine the result set which
* will be counted.
* @return The number of entities of the given type which match the specified query.
*/
public <K> int count(Class<? extends RawEntity<K>> type, Query query) throws SQLException {
int back = -1;
Connection conn = getProvider().getConnection();
try {
String sql = null;
tableNameConverterLock.readLock().lock();
try {
sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), true);
} finally {
tableNameConverterLock.readLock().unlock();
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql);
provider.setQueryStatementProperties(stmt, query);
query.setParameters(this, stmt);
ResultSet res = stmt.executeQuery();
if (res.next()) {
back = res.getInt(1);
}
res.close();
stmt.close();
} finally {
conn.close();
}
return back;
}
/**
* <p>Specifies the {@link TableNameConverter} instance to use for
* name conversion of all entity types. Name conversion is the process
* of determining the appropriate table name from an arbitrary interface
* extending {@link RawEntity}.</p>
*
* <p>The default table name converter is {@link CamelCaseTableNameConverter}.</p>
*
* @see #getTableNameConverter()
*/
public void setTableNameConverter(TableNameConverter tableNameConverter) {
tableNameConverterLock.writeLock().lock();
try {
this.tableNameConverter = tableNameConverter;
} finally {
tableNameConverterLock.writeLock().unlock();
}
}
/**
* Retrieves the {@link TableNameConverter} instance used for name
* conversion of all entity types.
*
* @see #setTableNameConverter(TableNameConverter)
*/
public TableNameConverter getTableNameConverter() {
tableNameConverterLock.readLock().lock();
try {
return tableNameConverter;
} finally {
tableNameConverterLock.readLock().unlock();
}
}
/**
* <p>Specifies the {@link FieldNameConverter} instance to use for
* field name conversion of all entity methods. Name conversion is the
* process of determining the appropriate field name from an arbitrary
* method within an interface extending {@link RawEntity}.</p>
*
* <p>The default field name converter is {@link CamelCaseFieldNameConverter}.</p>
*
* @see #getFieldNameConverter()
*/
public void setFieldNameConverter(FieldNameConverter fieldNameConverter) {
fieldNameConverterLock.writeLock().lock();
try {
this.fieldNameConverter = fieldNameConverter;
} finally {
fieldNameConverterLock.writeLock().unlock();
}
}
/**
* Retrieves the {@link FieldNameConverter} instance used for name
* conversion of all entity methods.
*
* @see #setFieldNameConverter(FieldNameConverter)
*/
public FieldNameConverter getFieldNameConverter() {
fieldNameConverterLock.readLock().lock();
try {
return fieldNameConverter;
} finally {
fieldNameConverterLock.readLock().unlock();
}
}
/**
* Specifies the {@link PolymorphicTypeMapper} instance to use for
* all flag value conversion of polymorphic types. The default type
* mapper is an empty {@link DefaultPolymorphicTypeMapper} instance
* (thus using the fully qualified classname for all values).
*
* @see #getPolymorphicTypeMapper()
*/
public void setPolymorphicTypeMapper(PolymorphicTypeMapper typeMapper) {
typeMapperLock.writeLock().lock();
try {
this.typeMapper = typeMapper;
if (typeMapper instanceof DefaultPolymorphicTypeMapper) {
((DefaultPolymorphicTypeMapper) typeMapper).resolveMappings(getTableNameConverter());
}
} finally {
typeMapperLock.writeLock().unlock();
}
}
/**
* Retrieves the {@link PolymorphicTypeMapper} instance used for flag
* value conversion of polymorphic types.
*
* @see #setPolymorphicTypeMapper(PolymorphicTypeMapper)
*/
public PolymorphicTypeMapper getPolymorphicTypeMapper() {
typeMapperLock.readLock().lock();
try {
if (typeMapper == null) {
throw new RuntimeException("No polymorphic type mapper was specified");
}
return typeMapper;
} finally {
typeMapperLock.readLock().unlock();
}
}
/**
* Sets the cache implementation to be used by all entities
* controlled by this manager. Note that this only affects
* <i>new</i> entities that have not yet been instantiated
* (may pre-exist as rows in the database). All old entities
* will continue to use the prior cache.
*/
public void setCache(Cache cache) {
cacheLock.writeLock().lock();
try {
if (!this.cache.equals(cache)) {
this.cache.dispose();
this.cache = cache;
}
} finally {
cacheLock.writeLock().unlock();
}
}
public Cache getCache() {
cacheLock.readLock().lock();
try {
return cache;
} finally {
cacheLock.readLock().unlock();
}
}
/**
* <p>Retrieves the database provider used by this <code>EntityManager</code>
* for all database operations. This method can be used reliably to obtain
* a database provider and hence a {@link Connection} instance which can
* be used for JDBC operations outside of ActiveObjects. Thus:</p>
*
* <pre>Connection conn = manager.getProvider().getConnection();
* try {
* // ...
* } finally {
* conn.close();
* }</pre>
*/
public DatabaseProvider getProvider() {
return provider;
}
<T extends RawEntity<K>, K> EntityProxy<T, K> getProxyForEntity(T entity) {
proxyLock.readLock().lock();
try {
return (EntityProxy<T, K>) proxies.get(entity);
} finally {
proxyLock.readLock().unlock();
}
}
RelationsCache getRelationsCache() {
return relationsCache;
}
private Reference<RawEntity<?>> createRef(RawEntity<?> entity) {
if (weaklyCache) {
return new WeakReference<RawEntity<?>>(entity);
}
return new SoftReference<RawEntity<?>>(entity);
}
private void verify(RawEntity<?> entity) {
if (entity.getEntityManager() != this) {
throw new RuntimeException("Entities can only be used with a single EntityManager instance");
}
}
private static interface Function<R, F> {
public R invoke(F formals);
}
private static class CacheKey<T> {
private T key;
private Class<? extends RawEntity<?>> type;
public CacheKey(T key, Class<? extends RawEntity<T>> type) {
this.key = key;
this.type = type;
}
@Override
public int hashCode() {
return (type.hashCode() + key.hashCode()) % (2 << 15);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CacheKey<?>) {
CacheKey<T> keyObj = (CacheKey<T>) obj;
if (key.equals(keyObj.key) && type.equals(keyObj.type)) {
return true;
}
}
return false;
}
}
}
| true | true | public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException {
List<T> back = new ArrayList<T>();
query.resolveFields(type, getFieldNameConverter());
// <ian>
Version version = type.getAnnotation(Version.class);
if (version != null && version.findInitial()) {
// Add initial version check to exclude
// objects that have only been created and not saved yet.
if (query.getWhereClause() == null) {
query.where(version.value() + " != ?", version.initial());
} else {
// Preserve existing WHERE clause and parameters
String whereClause = new StringBuilder().append(query.getWhereClause())
.append(" AND ").append(version.value()).append(" != ?").toString();
Object[] paramsOld = query.getWhereParams();
Object[] paramsNew = new Object[paramsOld.length + 1];
System.arraycopy(paramsOld, 0, paramsNew, 0, paramsOld.length);
paramsNew[paramsNew.length - 1] = version.initial();
query.setWhereClause(whereClause);
query.setWhereParams(paramsNew);
}
}
// </ian>
Preload preloadAnnotation = type.getAnnotation(Preload.class);
if (preloadAnnotation != null) {
if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) {
String[] oldFields = query.getFields();
List<String> newFields = new ArrayList<String>();
for (String newField : preloadAnnotation.value()) {
newField = newField.trim();
int fieldLoc = -1;
for (int i = 0; i < oldFields.length; i++) {
if (oldFields[i].equals(newField)) {
fieldLoc = i;
break;
}
}
if (fieldLoc < 0) {
newFields.add(newField);
} else {
newFields.add(oldFields[fieldLoc]);
}
}
if (!newFields.contains("*")) {
for (String oldField : oldFields) {
if (!newFields.contains(oldField)) {
newFields.add(oldField);
}
}
}
query.setFields(newFields.toArray(new String[newFields.size()]));
}
}
Connection conn = getProvider().getConnection();
try {
String sql = null;
tableNameConverterLock.readLock().lock();
try {
sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false);
} finally {
tableNameConverterLock.readLock().unlock();
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
provider.setQueryStatementProperties(stmt, query);
query.setParameters(this, stmt);
ResultSet res = stmt.executeQuery();
provider.setQueryResultSetProperties(res, query);
while (res.next()) {
T entity = peer(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field));
CacheLayer cacheLayer = getProxyForEntity(entity).getCacheLayer(entity);
for (String cacheField : query.getCanonicalFields(type, fieldNameConverter)) {
cacheLayer.put(cacheField, res.getObject(cacheField));
}
back.add(entity);
}
res.close();
stmt.close();
} finally {
conn.close();
}
return back.toArray((T[]) Array.newInstance(type, back.size()));
}
| public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException {
List<T> back = new ArrayList<T>();
query.resolveFields(type, getFieldNameConverter());
// <ian>
Version version = type.getAnnotation(Version.class);
if (version != null && !version.findInitial()) {
// Add initial version check to exclude
// objects that have only been created and not saved yet.
if (query.getWhereClause() == null) {
query.where(version.value() + " != ?", version.initial());
} else {
// Preserve existing WHERE clause and parameters
String whereClause = new StringBuilder().append(query.getWhereClause())
.append(" AND ").append(version.value()).append(" != ?").toString();
Object[] paramsOld = query.getWhereParams();
Object[] paramsNew = new Object[paramsOld.length + 1];
System.arraycopy(paramsOld, 0, paramsNew, 0, paramsOld.length);
paramsNew[paramsNew.length - 1] = version.initial();
query.setWhereClause(whereClause);
query.setWhereParams(paramsNew);
}
}
// </ian>
Preload preloadAnnotation = type.getAnnotation(Preload.class);
if (preloadAnnotation != null) {
if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) {
String[] oldFields = query.getFields();
List<String> newFields = new ArrayList<String>();
for (String newField : preloadAnnotation.value()) {
newField = newField.trim();
int fieldLoc = -1;
for (int i = 0; i < oldFields.length; i++) {
if (oldFields[i].equals(newField)) {
fieldLoc = i;
break;
}
}
if (fieldLoc < 0) {
newFields.add(newField);
} else {
newFields.add(oldFields[fieldLoc]);
}
}
if (!newFields.contains("*")) {
for (String oldField : oldFields) {
if (!newFields.contains(oldField)) {
newFields.add(oldField);
}
}
}
query.setFields(newFields.toArray(new String[newFields.size()]));
}
}
Connection conn = getProvider().getConnection();
try {
String sql = null;
tableNameConverterLock.readLock().lock();
try {
sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false);
} finally {
tableNameConverterLock.readLock().unlock();
}
Logger.getLogger("net.java.ao").log(Level.INFO, sql);
PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
provider.setQueryStatementProperties(stmt, query);
query.setParameters(this, stmt);
ResultSet res = stmt.executeQuery();
provider.setQueryResultSetProperties(res, query);
while (res.next()) {
T entity = peer(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field));
CacheLayer cacheLayer = getProxyForEntity(entity).getCacheLayer(entity);
for (String cacheField : query.getCanonicalFields(type, fieldNameConverter)) {
cacheLayer.put(cacheField, res.getObject(cacheField));
}
back.add(entity);
}
res.close();
stmt.close();
} finally {
conn.close();
}
return back.toArray((T[]) Array.newInstance(type, back.size()));
}
|
diff --git a/framework/src/com/phonegap/DroidGap.java b/framework/src/com/phonegap/DroidGap.java
index 2eee859b..fdf61b75 100755
--- a/framework/src/com/phonegap/DroidGap.java
+++ b/framework/src/com/phonegap/DroidGap.java
@@ -1,1987 +1,1987 @@
/*
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 com.phonegap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.HttpAuthHandler;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.phonegap.api.IPlugin;
import com.phonegap.api.LOG;
import com.phonegap.api.PhonegapActivity;
import com.phonegap.api.PluginManager;
/**
* This class is the main Android activity that represents the PhoneGap
* application. It should be extended by the user to load the specific
* html file that contains the application.
*
* As an example:
*
* package com.phonegap.examples;
* import android.app.Activity;
* import android.os.Bundle;
* import com.phonegap.*;
*
* public class Examples extends DroidGap {
* @Override
* public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
*
* // Set properties for activity
* super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog
* super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl().
*
* // Initialize activity
* super.init();
*
* // Clear cache if you want
* super.appView.clearCache(true);
*
* // Load your application
* super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory
* super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app
* }
* }
*
* Properties: The application can be configured using the following properties:
*
* // Display a native loading dialog when loading app. Format for value = "Title,Message".
* // (String - default=null)
* super.setStringProperty("loadingDialog", "Wait,Loading Demo...");
*
* // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message".
* // (String - default=null)
* super.setStringProperty("loadingPageDialog", "Loading page...");
*
* // Load a splash screen image from the resource drawable directory.
* // (Integer - default=0)
* super.setIntegerProperty("splashscreen", R.drawable.splash);
*
* // Set the background color.
* // (Integer - default=0 or BLACK)
* super.setIntegerProperty("backgroundColor", Color.WHITE);
*
* // Time in msec to wait before triggering a timeout error when loading
* // with super.loadUrl(). (Integer - default=20000)
* super.setIntegerProperty("loadUrlTimeoutValue", 60000);
*
* // URL to load if there's an error loading specified URL with loadUrl().
* // Should be a local URL starting with file://. (String - default=null)
* super.setStringProperty("errorUrl", "file:///android_asset/www/error.html");
*
* // Enable app to keep running in background. (Boolean - default=true)
* super.setBooleanProperty("keepRunning", false);
*
* Phonegap.xml configuration:
* PhoneGap uses a configuration file at res/xml/phonegap.xml to specify the following settings.
*
* Approved list of URLs that can be loaded into DroidGap
* <access origin="http://server regexp" subdomains="true" />
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*
* Phonegap plugins:
* PhoneGap uses a file at res/xml/plugins.xml to list all plugins that are installed.
* Before using a new plugin, a new element must be added to the file.
* name attribute is the service name passed to PhoneGap.exec() in JavaScript
* value attribute is the Java class name to call.
*
* <plugins>
* <plugin name="App" value="com.phonegap.App"/>
* ...
* </plugins>
*/
public class DroidGap extends PhonegapActivity {
public static String TAG = "DroidGap";
// The webview for our app
protected WebView appView;
protected WebViewClient webViewClient;
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>();
protected LinearLayout root;
public boolean bound = false;
public CallbackServer callbackServer;
protected PluginManager pluginManager;
protected boolean cancelLoadUrl = false;
protected ProgressDialog spinnerDialog = null;
// The initial URL for our app
// ie http://server/path/index.html#abc?query
private String url = null;
private Stack<String> urls = new Stack<String>();
// Url was specified from extras (activity was started programmatically)
private String initUrl = null;
private static int ACTIVITY_STARTING = 0;
private static int ACTIVITY_RUNNING = 1;
private static int ACTIVITY_EXITING = 2;
private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down
// The base of the initial URL for our app.
// Does not include file name. Ends with /
// ie http://server/path/
private String baseUrl = null;
// Plugin to call when activity result is received
protected IPlugin activityResultCallback = null;
protected boolean activityResultKeepRunning;
// Flag indicates that a loadUrl timeout occurred
private int loadUrlTimeout = 0;
// Default background color for activity
// (this is not the color for the webview, which is set in HTML)
private int backgroundColor = Color.BLACK;
/** The authorization tokens. */
private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
/*
* The variables below are used to cache some of the activity properties.
*/
// Draw a splash screen using an image located in the drawable resource directory.
// This is not the same as calling super.loadSplashscreen(url)
protected int splashscreen = 0;
// LoadUrl timeout value in msec (default of 20 sec)
protected int loadUrlTimeoutValue = 20000;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
private boolean classicRender;
/**
* Sets the authentication token.
*
* @param authenticationToken
* the authentication token
* @param host
* the host
* @param realm
* the realm
*/
public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
if(host == null) {
host = "";
}
if(realm == null) {
realm = "";
}
authenticationTokens.put(host.concat(realm), authenticationToken);
}
/**
* Removes the authentication token.
*
* @param host
* the host
* @param realm
* the realm
* @return the authentication token or null if did not exist
*/
public AuthenticationToken removeAuthenticationToken(String host, String realm) {
return authenticationTokens.remove(host.concat(realm));
}
/**
* Gets the authentication token.
*
* In order it tries:
* 1- host + realm
* 2- host
* 3- realm
* 4- no host, no realm
*
* @param host
* the host
* @param realm
* the realm
* @return the authentication token
*/
public AuthenticationToken getAuthenticationToken(String host, String realm) {
AuthenticationToken token = null;
token = authenticationTokens.get(host.concat(realm));
if(token == null) {
// try with just the host
token = authenticationTokens.get(host);
// Try the realm
if(token == null) {
token = authenticationTokens.get(realm);
}
// if no host found, just query for default
if(token == null) {
token = authenticationTokens.get("");
}
}
return token;
}
/**
* Clear all authentication tokens.
*/
public void clearAuthenticationTokens() {
authenticationTokens.clear();
}
/**
* Called when the activity is first created.
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
LOG.d(TAG, "DroidGap.onCreate()");
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket!
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
root = new LinearLayoutSoftKeyboardDetect(this, width, height);
root.setOrientation(LinearLayout.VERTICAL);
root.setBackgroundColor(this.backgroundColor);
root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
// Load PhoneGap configuration:
// white list of allowed URLs
// debug setting
this.loadConfiguration();
// If url was passed in to intent, then init webview, which will load the url
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
String url = bundle.getString("url");
if (url != null) {
this.initUrl = url;
}
}
// Setup the hardware volume controls to handle volume control
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
/**
* Create and initialize web container.
*/
public void init() {
LOG.d(TAG, "DroidGap.init()");
// Create web container
this.appView = new WebView(DroidGap.this);
this.appView.setId(100);
this.appView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT,
1.0F));
this.appView.setWebChromeClient(new GapClient(DroidGap.this));
this.setWebViewClient(this.appView, new GapViewClient(this));
//14 is Ice Cream Sandwich!
if(android.os.Build.VERSION.SDK_INT < 14 && this.classicRender)
{
//This hack fixes legacy PhoneGap apps
//We should be using real pixels, not pretend pixels
final float scale = getResources().getDisplayMetrics().density;
int initialScale = (int) (scale * 100);
this.appView.setInitialScale(initialScale);
}
else
{
this.appView.setInitialScale(0);
}
this.appView.setVerticalScrollBarEnabled(false);
this.appView.requestFocusFromTouch();
// Enable JavaScript
WebSettings settings = this.appView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
//Set the nav dump for HTC
settings.setNavDump(true);
// Enable database
settings.setDatabaseEnabled(true);
String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
// Enable DOM storage
settings.setDomStorageEnabled(true);
// Enable built-in geolocation
settings.setGeolocationEnabled(true);
// Add web view but make it invisible while loading URL
this.appView.setVisibility(View.INVISIBLE);
root.addView(this.appView);
setContentView(root);
// Clear cancel flag
this.cancelLoadUrl = false;
}
/**
* Set the WebViewClient.
*
* @param appView
* @param client
*/
protected void setWebViewClient(WebView appView, WebViewClient client) {
this.webViewClient = client;
appView.setWebViewClient(client);
}
/**
* Look at activity parameters and process them.
* This must be called from the main UI thread.
*/
private void handleActivityParameters() {
// If backgroundColor
this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK);
this.root.setBackgroundColor(this.backgroundColor);
// If spashscreen
this.splashscreen = this.getIntegerProperty("splashscreen", 0);
if ((this.urls.size() == 0) && (this.splashscreen != 0)) {
root.setBackgroundResource(this.splashscreen);
}
// If loadUrlTimeoutValue
int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0);
if (timeout > 0) {
this.loadUrlTimeoutValue = timeout;
}
// If keepRunning
this.keepRunning = this.getBooleanProperty("keepRunning", true);
}
/**
* Load the url into the webview.
*
* @param url
*/
public void loadUrl(String url) {
// If first page of app, then set URL to load to be the one passed in
if (this.initUrl == null || (this.urls.size() > 0)) {
this.loadUrlIntoView(url);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(this.initUrl);
}
}
/**
* Load the url into the webview.
*
* @param url
*/
private void loadUrlIntoView(final String url) {
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap.loadUrl(%s)", url);
}
this.url = url;
if (this.baseUrl == null) {
int i = url.lastIndexOf('/');
if (i > 0) {
this.baseUrl = url.substring(0, i+1);
}
else {
this.baseUrl = this.url + "/";
}
}
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl);
}
// Load URL on UI thread
final DroidGap me = this;
this.runOnUiThread(new Runnable() {
public void run() {
// Init web view if not already done
if (me.appView == null) {
me.init();
}
// Handle activity parameters
me.handleActivityParameters();
// Track URLs loaded instead of using appView history
me.urls.push(url);
me.appView.clearHistory();
// Create callback server and plugin manager
if (me.callbackServer == null) {
me.callbackServer = new CallbackServer();
me.callbackServer.init(url);
}
else {
me.callbackServer.reinit(url);
}
if (me.pluginManager == null) {
me.pluginManager = new PluginManager(me.appView, me);
}
else {
me.pluginManager.reinit();
}
// If loadingDialog property, then show the App loading dialog for first page of app
String loading = null;
if (me.urls.size() == 1) {
loading = me.getStringProperty("loadingDialog", null);
}
else {
loading = me.getStringProperty("loadingPageDialog", null);
}
if (loading != null) {
String title = "";
String message = "Loading Application...";
if (loading.length() > 0) {
int comma = loading.indexOf(',');
if (comma > 0) {
title = loading.substring(0, comma);
message = loading.substring(comma+1);
}
else {
title = "";
message = loading;
}
}
me.spinnerStart(title, message);
}
// Create a timeout timer for loadUrl
final int currentLoadUrlTimeout = me.loadUrlTimeout;
Runnable runnable = new Runnable() {
public void run() {
try {
synchronized(this) {
wait(me.loadUrlTimeoutValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// If timeout, then stop loading and handle error
if (me.loadUrlTimeout == currentLoadUrlTimeout) {
me.appView.stopLoading();
LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient");
me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
me.appView.loadUrl(url);
}
});
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrl(final String url, int time) {
// If first page of app, then set URL to load to be the one passed in
if (this.initUrl == null || (this.urls.size() > 0)) {
this.loadUrlIntoView(url, time);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(this.initUrl);
}
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
private void loadUrlIntoView(final String url, final int time) {
// Clear cancel flag
this.cancelLoadUrl = false;
// If not first page of app, then load immediately
if (this.urls.size() > 0) {
this.loadUrlIntoView(url);
}
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time);
}
final DroidGap me = this;
// Handle activity parameters
this.runOnUiThread(new Runnable() {
public void run() {
if (me.appView == null) {
me.init();
}
me.handleActivityParameters();
}
});
Runnable runnable = new Runnable() {
public void run() {
try {
synchronized(this) {
this.wait(time);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!me.cancelLoadUrl) {
me.loadUrlIntoView(url);
}
else{
me.cancelLoadUrl = false;
LOG.d(TAG, "Aborting loadUrl(%s): Another URL was loaded before timer expired.", url);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
/**
* Cancel loadUrl before it has been loaded.
*/
public void cancelLoadUrl() {
this.cancelLoadUrl = true;
}
/**
* Clear the resource cache.
*/
public void clearCache() {
if (this.appView == null) {
this.init();
}
this.appView.clearCache(true);
}
/**
* Clear web history in this web view.
*/
public void clearHistory() {
this.urls.clear();
this.appView.clearHistory();
// Leave current url on history stack
if (this.url != null) {
this.urls.push(this.url);
}
}
/**
* Go to previous page in history. (We manage our own history)
*
* @return true if we went back, false if we are already at top
*/
public boolean backHistory() {
// Check webview first to see if there is a history
// This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior)
if (this.appView.canGoBack()) {
this.appView.goBack();
return true;
}
// If our managed history has prev url
if (this.urls.size() > 1) {
this.urls.pop(); // Pop current url
String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl()
this.loadUrl(url);
return true;
}
return false;
}
@Override
/**
* Called by the system when the device configuration changes while your activity is running.
*
* @param Configuration newConfig
*/
public void onConfigurationChanged(Configuration newConfig) {
//don't reload the current page when the orientation is changed
super.onConfigurationChanged(newConfig);
}
/**
* Get boolean property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public boolean getBooleanProperty(String name, boolean defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Boolean p = (Boolean)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.booleanValue();
}
/**
* Get int property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public int getIntegerProperty(String name, int defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Integer p = (Integer)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.intValue();
}
/**
* Get string property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public String getStringProperty(String name, String defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
String p = bundle.getString(name);
if (p == null) {
return defaultValue;
}
return p;
}
/**
* Get double property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public double getDoubleProperty(String name, double defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Double p = (Double)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.doubleValue();
}
/**
* Set boolean property on activity.
*
* @param name
* @param value
*/
public void setBooleanProperty(String name, boolean value) {
this.getIntent().putExtra(name, value);
}
/**
* Set int property on activity.
*
* @param name
* @param value
*/
public void setIntegerProperty(String name, int value) {
this.getIntent().putExtra(name, value);
}
/**
* Set string property on activity.
*
* @param name
* @param value
*/
public void setStringProperty(String name, String value) {
this.getIntent().putExtra(name, value);
}
/**
* Set double property on activity.
*
* @param name
* @param value
*/
public void setDoubleProperty(String name, double value) {
this.getIntent().putExtra(name, value);
}
@Override
/**
* Called when the system is about to start resuming a previous activity.
*/
protected void onPause() {
super.onPause();
// Don't process pause if shutting down, since onDestroy() will be called
if (this.activityState == ACTIVITY_EXITING) {
return;
}
if (this.appView == null) {
return;
}
// Send pause event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.fireDocumentEvent('pause');}catch(e){};");
// Forward to plugins
this.pluginManager.onPause(this.keepRunning);
// If app doesn't want to run in background
if (!this.keepRunning) {
// Pause JavaScript timers (including setInterval)
this.appView.pauseTimers();
}
}
@Override
/**
* Called when the activity receives a new intent
**/
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Forward to plugins
this.pluginManager.onNewIntent(intent);
}
@Override
/**
* Called when the activity will start interacting with the user.
*/
protected void onResume() {
super.onResume();
if (this.activityState == ACTIVITY_STARTING) {
this.activityState = ACTIVITY_RUNNING;
return;
}
if (this.appView == null) {
return;
}
// Send resume event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.fireDocumentEvent('resume');}catch(e){};");
// Forward to plugins
this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning);
// If app doesn't want to run in background
if (!this.keepRunning || this.activityResultKeepRunning) {
// Restore multitasking state
if (this.activityResultKeepRunning) {
this.keepRunning = this.activityResultKeepRunning;
this.activityResultKeepRunning = false;
}
// Resume JavaScript timers (including setInterval)
this.appView.resumeTimers();
}
}
@Override
/**
* The final call you receive before your activity is destroyed.
*/
public void onDestroy() {
super.onDestroy();
if (this.appView != null) {
// Send destroy event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.onDestroy.fire();}catch(e){};");
// Load blank page so that JavaScript onunload is called
this.appView.loadUrl("about:blank");
// Forward to plugins
this.pluginManager.onDestroy();
}
else {
this.endActivity();
}
}
/**
* Send a message to all plugins.
*
* @param id The message id
* @param data The message data
*/
public void postMessage(String id, Object data) {
// Forward to plugins
this.pluginManager.postMessage(id, data);
}
/**
* @deprecated
* Add services to res/xml/plugins.xml instead.
*
* Add a class that implements a service.
*
* @param serviceType
* @param className
*/
@Deprecated
public void addService(String serviceType, String className) {
this.pluginManager.addService(serviceType, className);
}
/**
* Send JavaScript statement back to JavaScript.
* (This is a convenience method)
*
* @param message
*/
public void sendJavascript(String statement) {
this.callbackServer.sendJavascript(statement);
}
/**
* Load the specified URL in the PhoneGap webview or a new browser instance.
*
* NOTE: If openExternal is false, only URLs listed in whitelist can be loaded.
*
* @param url The url to load.
* @param openExternal Load url in browser instead of PhoneGap webview.
* @param clearHistory Clear the history stack, so new page becomes top of history
* @param params DroidGap parameters for new app
*/
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
this.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) {
// TODO: What about params?
// Clear out current url from history, since it will be replacing it
if (clearHistory) {
this.urls.clear();
}
// Load new URL
this.loadUrl(url);
}
// Load in default viewer if not
else {
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")");
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
// Load in default view intent
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
/**
* Show the spinner. Must be called from the UI thread.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public void spinnerStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final DroidGap me = this;
this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
me.spinnerDialog = null;
}
});
}
/**
* Stop spinner.
*/
public void spinnerStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Set the chrome handler.
*/
public class GapClient extends WebChromeClient {
private String TAG = "PhoneGapLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapClient(Context ctx) {
this.ctx = (DroidGap)ctx;
}
/**
* Tell the client to display a javascript alert dialog.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Alert");
//Don't let alerts break the back button
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.confirm();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a confirm dialog to the user.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Confirm");
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.cancel();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
reqOk = true;
}
// Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
try {
array = new JSONArray(defaultValue.substring(4));
String service = array.getString(0);
String action = array.getString(1);
String callbackId = array.getString(2);
boolean async = array.getBoolean(3);
String r = pluginManager.exec(service, action, callbackId, message, async);
result.confirm(r);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = callbackServer.getJavascript();
result.confirm(r);
}
// Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = "";
if (message.equals("usePolling")) {
r = ""+callbackServer.usePolling();
}
else if (message.equals("restartServer")) {
callbackServer.restartServer();
}
else if (message.equals("getPort")) {
r = Integer.toString(callbackServer.getPort());
}
else if (message.equals("getToken")) {
r = callbackServer.getToken();
}
result.confirm(r);
}
// PhoneGap JS has initialized, so show webview
// (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
result.confirm("OK");
}
// Show dialog
else {
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
final EditText input = new EditText(this.ctx);
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
return true;
}
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if( estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@Override
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* The webview client receives notifications about appView
*/
public class GapViewClient extends WebViewClient {
DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapViewClient(DroidGap ctx) {
this.ctx = ctx;
}
/**
* Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return true to override, false for default behavior
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves
if (this.ctx.pluginManager.onOverrideUrlLoading(url)) {
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
}
}
// If displaying map (geo:0,0?q=address)
else if (url.startsWith("geo:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
}
}
// If sending email (mailto:[email protected])
else if (url.startsWith(WebView.SCHEME_MAILTO)) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:"+address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
}
}
// All else
else {
// If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity.
// Our app continues to run. When BACK is pressed, our app is redisplayed.
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
this.ctx.loadUrl(url);
}
// If not our application, let default viewer handle
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
return true;
}
/**
* On received http auth request.
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
*
* @param view
* the view
* @param handler
* the handler
* @param host
* the host
* @param realm
* the realm
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) {
// get the authentication token
AuthenticationToken token = getAuthenticationToken(host,realm);
if(token != null) {
handler.proceed(token.getUserName(), token.getPassword());
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager.
view.clearHistory();
}
/**
* Notify the host application that a page has finished loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Try firing the onNativeReady event in JS. If it fails because the JS is
// not loaded yet then just set a flag so that the onNativeReady can be fired
// from the JS side when the JS gets to that code.
if (!url.equals("about:blank")) {
appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}");
}
// Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly
if (appView.getVisibility() == View.INVISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
ctx.runOnUiThread(new Runnable() {
public void run() {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
}
});
} catch (InterruptedException e) {
}
}
});
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
if (this.ctx.callbackServer != null) {
this.ctx.callbackServer.destroy();
}
this.ctx.endActivity();
}
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Stop "app loading" spinner if showing
this.ctx.spinnerStop();
// Handle error
this.ctx.onReceivedError(errorCode, description, failingUrl);
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// debug = true
handler.proceed();
return;
} else {
// debug = false
super.onReceivedSslError(view, handler, error);
}
} catch (NameNotFoundException e) {
// When it doubt, lock it out!
super.onReceivedSslError(view, handler, error);
}
}
}
/**
* End this activity by calling finish for activity
*/
public void endActivity() {
this.activityState = ACTIVITY_EXITING;
this.finish();
}
/**
* Called when a key is pressed.
*
* @param keyCode
* @param event
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (this.appView == null) {
return super.onKeyDown(keyCode, event);
}
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');");
return true;
}
// If not bound
else {
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
return true;
}
// If not, then invoke behavior of super class
else {
this.activityState = ACTIVITY_EXITING;
return super.onKeyDown(keyCode, event);
}
}
}
// If menu key
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');");
return super.onKeyDown(keyCode, event);
}
// If search key
else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');");
return true;
}
return false;
}
/**
* Any calls to Activity.startActivityForResult must use method below, so
* the result can be routed to them correctly.
*
* This is done to eliminate the need to modify DroidGap.java to receive activity results.
*
* @param intent The intent to start
* @param requestCode Identifies who to send the result to
*
* @throws RuntimeException
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException {
LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode);
super.startActivityForResult(intent, requestCode);
}
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(IPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
@Override
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
IPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
@Override
public void setActivityResultCallback(IPlugin plugin) {
this.activityResultCallback = plugin;
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final DroidGap me = this;
// If errorUrl specified, then load it
final String errorUrl = me.getStringProperty("errorUrl", null);
if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.setVisibility(View.GONE);
me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true);
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*
* @param title
* @param message
* @param button
* @param exit
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final DroidGap me = this;
me.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
me.endActivity();
}
}
});
dlg.create();
dlg.show();
}
});
}
/**
* We are providing this class to detect when the soft keyboard is shown
* and hidden in the web view.
*/
class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private static final String TAG = "SoftKeyboardDetect";
private int oldHeight = 0; // Need to save the old height as not to send redundant events
private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0;
private int screenHeight = 0;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context);
screenWidth = width;
screenHeight = height;
}
@Override
/**
* Start listening to new measurement events. Fire events when the height
* gets smaller fire a show keyboard event and when height gets bigger fire
* a hide keyboard event.
*
* Note: We are using callbackServer.sendJavascript() instead of
* this.appView.loadUrl() as changing the URL of the app would cause the
* soft keyboard to go away.
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
LOG.v(TAG, "We are in our onMeasure method");
// Get the current height of the visible part of the screen.
// This height will not included the status bar.
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
LOG.v(TAG, "Old Height = %d", oldHeight);
LOG.v(TAG, "Height = %d", height);
LOG.v(TAG, "Old Width = %d", oldWidth);
LOG.v(TAG, "Width = %d", width);
// If the oldHeight = 0 then this is the first measure event as the app starts up.
// If oldHeight == height then we got a measurement change that doesn't affect us.
if (oldHeight == 0 || oldHeight == height) {
LOG.d(TAG, "Ignore this event");
}
// Account for orientation change and ignore this event/Fire orientation change
else if(screenHeight == width)
{
int tmp_var = screenHeight;
screenHeight = screenWidth;
screenWidth = tmp_var;
LOG.v(TAG, "Orientation Change");
}
// If the height as gotten bigger then we will assume the soft keyboard has
// gone away.
else if (height > oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw hide keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');");
}
}
// If the height as gotten smaller then we will assume the soft keyboard has
// been displayed.
else if (height < oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw show keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');");
}
}
// Update the old height for the next event
oldHeight = height;
oldWidth = width;
}
}
/**
* Load PhoneGap configuration from res/xml/phonegap.xml.
* Approved list of URLs that can be loaded into DroidGap
* <access origin="http://server regexp" subdomains="true" />
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*/
private void loadConfiguration() {
int id = getResources().getIdentifier("phonegap", "xml", getPackageName());
if (id == 0) {
LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("PhoneGapLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
else if(strNode.equals("render")) {
String enabled = xml.getAttributeValue(null, "enabled");
if(enabled != null)
{
this.classicRender = enabled.equals("true");
}
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
private void addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if(origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
- whiteList.add(Pattern.compile("*"));
+ whiteList.add(Pattern.compile(".*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
if (subdomains) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
- whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*")));
+ whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
} else {
- whiteList.add(Pattern.compile("^https{0,1}://.*"+origin));
+ whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
- whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://")));
+ whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
} else {
- whiteList.add(Pattern.compile("^https{0,1}://"+origin));
+ whiteList.add(Pattern.compile("^https?://"+origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch(Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
private boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
whiteListCache.put(url, true);
return true;
}
}
return false;
}
/*
* Hook in DroidGap for menu plugins
*
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.postMessage("onCreateOptionsMenu", menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
this.postMessage("onPrepareOptionsMenu", menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
this.postMessage("onOptionsItemSelected", item);
return true;
}
}
| false | true | public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
this.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) {
// TODO: What about params?
// Clear out current url from history, since it will be replacing it
if (clearHistory) {
this.urls.clear();
}
// Load new URL
this.loadUrl(url);
}
// Load in default viewer if not
else {
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")");
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
// Load in default view intent
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
/**
* Show the spinner. Must be called from the UI thread.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public void spinnerStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final DroidGap me = this;
this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
me.spinnerDialog = null;
}
});
}
/**
* Stop spinner.
*/
public void spinnerStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Set the chrome handler.
*/
public class GapClient extends WebChromeClient {
private String TAG = "PhoneGapLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapClient(Context ctx) {
this.ctx = (DroidGap)ctx;
}
/**
* Tell the client to display a javascript alert dialog.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Alert");
//Don't let alerts break the back button
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.confirm();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a confirm dialog to the user.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Confirm");
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.cancel();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
reqOk = true;
}
// Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
try {
array = new JSONArray(defaultValue.substring(4));
String service = array.getString(0);
String action = array.getString(1);
String callbackId = array.getString(2);
boolean async = array.getBoolean(3);
String r = pluginManager.exec(service, action, callbackId, message, async);
result.confirm(r);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = callbackServer.getJavascript();
result.confirm(r);
}
// Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = "";
if (message.equals("usePolling")) {
r = ""+callbackServer.usePolling();
}
else if (message.equals("restartServer")) {
callbackServer.restartServer();
}
else if (message.equals("getPort")) {
r = Integer.toString(callbackServer.getPort());
}
else if (message.equals("getToken")) {
r = callbackServer.getToken();
}
result.confirm(r);
}
// PhoneGap JS has initialized, so show webview
// (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
result.confirm("OK");
}
// Show dialog
else {
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
final EditText input = new EditText(this.ctx);
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
return true;
}
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if( estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@Override
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* The webview client receives notifications about appView
*/
public class GapViewClient extends WebViewClient {
DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapViewClient(DroidGap ctx) {
this.ctx = ctx;
}
/**
* Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return true to override, false for default behavior
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves
if (this.ctx.pluginManager.onOverrideUrlLoading(url)) {
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
}
}
// If displaying map (geo:0,0?q=address)
else if (url.startsWith("geo:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
}
}
// If sending email (mailto:[email protected])
else if (url.startsWith(WebView.SCHEME_MAILTO)) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:"+address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
}
}
// All else
else {
// If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity.
// Our app continues to run. When BACK is pressed, our app is redisplayed.
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
this.ctx.loadUrl(url);
}
// If not our application, let default viewer handle
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
return true;
}
/**
* On received http auth request.
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
*
* @param view
* the view
* @param handler
* the handler
* @param host
* the host
* @param realm
* the realm
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) {
// get the authentication token
AuthenticationToken token = getAuthenticationToken(host,realm);
if(token != null) {
handler.proceed(token.getUserName(), token.getPassword());
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager.
view.clearHistory();
}
/**
* Notify the host application that a page has finished loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Try firing the onNativeReady event in JS. If it fails because the JS is
// not loaded yet then just set a flag so that the onNativeReady can be fired
// from the JS side when the JS gets to that code.
if (!url.equals("about:blank")) {
appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}");
}
// Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly
if (appView.getVisibility() == View.INVISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
ctx.runOnUiThread(new Runnable() {
public void run() {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
}
});
} catch (InterruptedException e) {
}
}
});
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
if (this.ctx.callbackServer != null) {
this.ctx.callbackServer.destroy();
}
this.ctx.endActivity();
}
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Stop "app loading" spinner if showing
this.ctx.spinnerStop();
// Handle error
this.ctx.onReceivedError(errorCode, description, failingUrl);
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// debug = true
handler.proceed();
return;
} else {
// debug = false
super.onReceivedSslError(view, handler, error);
}
} catch (NameNotFoundException e) {
// When it doubt, lock it out!
super.onReceivedSslError(view, handler, error);
}
}
}
/**
* End this activity by calling finish for activity
*/
public void endActivity() {
this.activityState = ACTIVITY_EXITING;
this.finish();
}
/**
* Called when a key is pressed.
*
* @param keyCode
* @param event
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (this.appView == null) {
return super.onKeyDown(keyCode, event);
}
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');");
return true;
}
// If not bound
else {
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
return true;
}
// If not, then invoke behavior of super class
else {
this.activityState = ACTIVITY_EXITING;
return super.onKeyDown(keyCode, event);
}
}
}
// If menu key
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');");
return super.onKeyDown(keyCode, event);
}
// If search key
else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');");
return true;
}
return false;
}
/**
* Any calls to Activity.startActivityForResult must use method below, so
* the result can be routed to them correctly.
*
* This is done to eliminate the need to modify DroidGap.java to receive activity results.
*
* @param intent The intent to start
* @param requestCode Identifies who to send the result to
*
* @throws RuntimeException
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException {
LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode);
super.startActivityForResult(intent, requestCode);
}
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(IPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
@Override
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
IPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
@Override
public void setActivityResultCallback(IPlugin plugin) {
this.activityResultCallback = plugin;
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final DroidGap me = this;
// If errorUrl specified, then load it
final String errorUrl = me.getStringProperty("errorUrl", null);
if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.setVisibility(View.GONE);
me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true);
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*
* @param title
* @param message
* @param button
* @param exit
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final DroidGap me = this;
me.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
me.endActivity();
}
}
});
dlg.create();
dlg.show();
}
});
}
/**
* We are providing this class to detect when the soft keyboard is shown
* and hidden in the web view.
*/
class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private static final String TAG = "SoftKeyboardDetect";
private int oldHeight = 0; // Need to save the old height as not to send redundant events
private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0;
private int screenHeight = 0;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context);
screenWidth = width;
screenHeight = height;
}
@Override
/**
* Start listening to new measurement events. Fire events when the height
* gets smaller fire a show keyboard event and when height gets bigger fire
* a hide keyboard event.
*
* Note: We are using callbackServer.sendJavascript() instead of
* this.appView.loadUrl() as changing the URL of the app would cause the
* soft keyboard to go away.
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
LOG.v(TAG, "We are in our onMeasure method");
// Get the current height of the visible part of the screen.
// This height will not included the status bar.
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
LOG.v(TAG, "Old Height = %d", oldHeight);
LOG.v(TAG, "Height = %d", height);
LOG.v(TAG, "Old Width = %d", oldWidth);
LOG.v(TAG, "Width = %d", width);
// If the oldHeight = 0 then this is the first measure event as the app starts up.
// If oldHeight == height then we got a measurement change that doesn't affect us.
if (oldHeight == 0 || oldHeight == height) {
LOG.d(TAG, "Ignore this event");
}
// Account for orientation change and ignore this event/Fire orientation change
else if(screenHeight == width)
{
int tmp_var = screenHeight;
screenHeight = screenWidth;
screenWidth = tmp_var;
LOG.v(TAG, "Orientation Change");
}
// If the height as gotten bigger then we will assume the soft keyboard has
// gone away.
else if (height > oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw hide keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');");
}
}
// If the height as gotten smaller then we will assume the soft keyboard has
// been displayed.
else if (height < oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw show keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');");
}
}
// Update the old height for the next event
oldHeight = height;
oldWidth = width;
}
}
/**
* Load PhoneGap configuration from res/xml/phonegap.xml.
* Approved list of URLs that can be loaded into DroidGap
* <access origin="http://server regexp" subdomains="true" />
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*/
private void loadConfiguration() {
int id = getResources().getIdentifier("phonegap", "xml", getPackageName());
if (id == 0) {
LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("PhoneGapLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
else if(strNode.equals("render")) {
String enabled = xml.getAttributeValue(null, "enabled");
if(enabled != null)
{
this.classicRender = enabled.equals("true");
}
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
private void addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if(origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
whiteList.add(Pattern.compile("*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
if (subdomains) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*")));
} else {
whiteList.add(Pattern.compile("^https{0,1}://.*"+origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://")));
} else {
whiteList.add(Pattern.compile("^https{0,1}://"+origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch(Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
private boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
whiteListCache.put(url, true);
return true;
}
}
return false;
}
/*
* Hook in DroidGap for menu plugins
*
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.postMessage("onCreateOptionsMenu", menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
this.postMessage("onPrepareOptionsMenu", menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
this.postMessage("onOptionsItemSelected", item);
return true;
}
}
| public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
this.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) {
// TODO: What about params?
// Clear out current url from history, since it will be replacing it
if (clearHistory) {
this.urls.clear();
}
// Load new URL
this.loadUrl(url);
}
// Load in default viewer if not
else {
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")");
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
// Load in default view intent
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
/**
* Show the spinner. Must be called from the UI thread.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public void spinnerStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final DroidGap me = this;
this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
me.spinnerDialog = null;
}
});
}
/**
* Stop spinner.
*/
public void spinnerStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Set the chrome handler.
*/
public class GapClient extends WebChromeClient {
private String TAG = "PhoneGapLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapClient(Context ctx) {
this.ctx = (DroidGap)ctx;
}
/**
* Tell the client to display a javascript alert dialog.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Alert");
//Don't let alerts break the back button
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.confirm();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a confirm dialog to the user.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Confirm");
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.cancel();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
reqOk = true;
}
// Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
try {
array = new JSONArray(defaultValue.substring(4));
String service = array.getString(0);
String action = array.getString(1);
String callbackId = array.getString(2);
boolean async = array.getBoolean(3);
String r = pluginManager.exec(service, action, callbackId, message, async);
result.confirm(r);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = callbackServer.getJavascript();
result.confirm(r);
}
// Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = "";
if (message.equals("usePolling")) {
r = ""+callbackServer.usePolling();
}
else if (message.equals("restartServer")) {
callbackServer.restartServer();
}
else if (message.equals("getPort")) {
r = Integer.toString(callbackServer.getPort());
}
else if (message.equals("getToken")) {
r = callbackServer.getToken();
}
result.confirm(r);
}
// PhoneGap JS has initialized, so show webview
// (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
result.confirm("OK");
}
// Show dialog
else {
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
final EditText input = new EditText(this.ctx);
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
return true;
}
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if( estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@Override
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* The webview client receives notifications about appView
*/
public class GapViewClient extends WebViewClient {
DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapViewClient(DroidGap ctx) {
this.ctx = ctx;
}
/**
* Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return true to override, false for default behavior
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves
if (this.ctx.pluginManager.onOverrideUrlLoading(url)) {
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
}
}
// If displaying map (geo:0,0?q=address)
else if (url.startsWith("geo:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
}
}
// If sending email (mailto:[email protected])
else if (url.startsWith(WebView.SCHEME_MAILTO)) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:"+address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
}
}
// All else
else {
// If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity.
// Our app continues to run. When BACK is pressed, our app is redisplayed.
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
this.ctx.loadUrl(url);
}
// If not our application, let default viewer handle
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
return true;
}
/**
* On received http auth request.
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
*
* @param view
* the view
* @param handler
* the handler
* @param host
* the host
* @param realm
* the realm
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) {
// get the authentication token
AuthenticationToken token = getAuthenticationToken(host,realm);
if(token != null) {
handler.proceed(token.getUserName(), token.getPassword());
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager.
view.clearHistory();
}
/**
* Notify the host application that a page has finished loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Try firing the onNativeReady event in JS. If it fails because the JS is
// not loaded yet then just set a flag so that the onNativeReady can be fired
// from the JS side when the JS gets to that code.
if (!url.equals("about:blank")) {
appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}");
}
// Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly
if (appView.getVisibility() == View.INVISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
ctx.runOnUiThread(new Runnable() {
public void run() {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
}
});
} catch (InterruptedException e) {
}
}
});
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
if (this.ctx.callbackServer != null) {
this.ctx.callbackServer.destroy();
}
this.ctx.endActivity();
}
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Stop "app loading" spinner if showing
this.ctx.spinnerStop();
// Handle error
this.ctx.onReceivedError(errorCode, description, failingUrl);
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// debug = true
handler.proceed();
return;
} else {
// debug = false
super.onReceivedSslError(view, handler, error);
}
} catch (NameNotFoundException e) {
// When it doubt, lock it out!
super.onReceivedSslError(view, handler, error);
}
}
}
/**
* End this activity by calling finish for activity
*/
public void endActivity() {
this.activityState = ACTIVITY_EXITING;
this.finish();
}
/**
* Called when a key is pressed.
*
* @param keyCode
* @param event
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (this.appView == null) {
return super.onKeyDown(keyCode, event);
}
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');");
return true;
}
// If not bound
else {
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
return true;
}
// If not, then invoke behavior of super class
else {
this.activityState = ACTIVITY_EXITING;
return super.onKeyDown(keyCode, event);
}
}
}
// If menu key
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');");
return super.onKeyDown(keyCode, event);
}
// If search key
else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');");
return true;
}
return false;
}
/**
* Any calls to Activity.startActivityForResult must use method below, so
* the result can be routed to them correctly.
*
* This is done to eliminate the need to modify DroidGap.java to receive activity results.
*
* @param intent The intent to start
* @param requestCode Identifies who to send the result to
*
* @throws RuntimeException
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException {
LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode);
super.startActivityForResult(intent, requestCode);
}
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(IPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
@Override
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
IPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
@Override
public void setActivityResultCallback(IPlugin plugin) {
this.activityResultCallback = plugin;
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final DroidGap me = this;
// If errorUrl specified, then load it
final String errorUrl = me.getStringProperty("errorUrl", null);
if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.setVisibility(View.GONE);
me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true);
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*
* @param title
* @param message
* @param button
* @param exit
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final DroidGap me = this;
me.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
me.endActivity();
}
}
});
dlg.create();
dlg.show();
}
});
}
/**
* We are providing this class to detect when the soft keyboard is shown
* and hidden in the web view.
*/
class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private static final String TAG = "SoftKeyboardDetect";
private int oldHeight = 0; // Need to save the old height as not to send redundant events
private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0;
private int screenHeight = 0;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context);
screenWidth = width;
screenHeight = height;
}
@Override
/**
* Start listening to new measurement events. Fire events when the height
* gets smaller fire a show keyboard event and when height gets bigger fire
* a hide keyboard event.
*
* Note: We are using callbackServer.sendJavascript() instead of
* this.appView.loadUrl() as changing the URL of the app would cause the
* soft keyboard to go away.
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
LOG.v(TAG, "We are in our onMeasure method");
// Get the current height of the visible part of the screen.
// This height will not included the status bar.
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
LOG.v(TAG, "Old Height = %d", oldHeight);
LOG.v(TAG, "Height = %d", height);
LOG.v(TAG, "Old Width = %d", oldWidth);
LOG.v(TAG, "Width = %d", width);
// If the oldHeight = 0 then this is the first measure event as the app starts up.
// If oldHeight == height then we got a measurement change that doesn't affect us.
if (oldHeight == 0 || oldHeight == height) {
LOG.d(TAG, "Ignore this event");
}
// Account for orientation change and ignore this event/Fire orientation change
else if(screenHeight == width)
{
int tmp_var = screenHeight;
screenHeight = screenWidth;
screenWidth = tmp_var;
LOG.v(TAG, "Orientation Change");
}
// If the height as gotten bigger then we will assume the soft keyboard has
// gone away.
else if (height > oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw hide keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');");
}
}
// If the height as gotten smaller then we will assume the soft keyboard has
// been displayed.
else if (height < oldHeight) {
if (callbackServer != null) {
LOG.v(TAG, "Throw show keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');");
}
}
// Update the old height for the next event
oldHeight = height;
oldWidth = width;
}
}
/**
* Load PhoneGap configuration from res/xml/phonegap.xml.
* Approved list of URLs that can be loaded into DroidGap
* <access origin="http://server regexp" subdomains="true" />
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*/
private void loadConfiguration() {
int id = getResources().getIdentifier("phonegap", "xml", getPackageName());
if (id == 0) {
LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("PhoneGapLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
else if(strNode.equals("render")) {
String enabled = xml.getAttributeValue(null, "enabled");
if(enabled != null)
{
this.classicRender = enabled.equals("true");
}
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
private void addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if(origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
whiteList.add(Pattern.compile(".*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
if (subdomains) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
} else {
whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
} else {
whiteList.add(Pattern.compile("^https?://"+origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch(Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
private boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
whiteListCache.put(url, true);
return true;
}
}
return false;
}
/*
* Hook in DroidGap for menu plugins
*
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.postMessage("onCreateOptionsMenu", menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
this.postMessage("onPrepareOptionsMenu", menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
this.postMessage("onOptionsItemSelected", item);
return true;
}
}
|
diff --git a/src/java/fedora/server/management/DBPIDGenerator.java b/src/java/fedora/server/management/DBPIDGenerator.java
index 5cdc89a31..4cc753381 100755
--- a/src/java/fedora/server/management/DBPIDGenerator.java
+++ b/src/java/fedora/server/management/DBPIDGenerator.java
@@ -1,196 +1,197 @@
package fedora.server.management;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.log4j.Logger;
import fedora.common.MalformedPIDException;
import fedora.common.PID;
import fedora.server.storage.ConnectionPool;
import fedora.server.utilities.SQLUtility;
/**
* A PIDGenerator that uses a database to keep track of the highest
* pid it knows about for each namespace.
*
* @author [email protected]
* @version $Id$
*/
public class DBPIDGenerator
implements PIDGenerator {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
DBPIDGenerator.class.getName());
private HashMap m_highestID;
private PID m_lastPID;
private ConnectionPool m_connectionPool;
/**
* Initialize the DBPIDGenerator.
*
* This initializes the memory hash with values in the database, if any.
*
* If oldPidGenDir is not null, the constructor will then call
* neverGeneratePID on the most recently generated PID as reported by
* the log files in that directory. This is to support automatic
* upgrade of this functionality from versions of Fedora prior to 1.2.
*/
public DBPIDGenerator(ConnectionPool cPool, File oldPidGenDir)
throws IOException {
m_connectionPool=cPool;
m_highestID=new HashMap();
// load the values from the database into the m_highestID hash
// pidGen: namespace highestID
Statement s=null;
ResultSet results=null;
Connection conn=null;
try {
conn=m_connectionPool.getConnection();
String query="SELECT namespace, highestID FROM pidGen";
s=conn.createStatement();
results=s.executeQuery(query);
while (results.next()) {
m_highestID.put(results.getString("namespace"),
new Integer(results.getInt("highestID")));
}
} catch (SQLException sqle) {
- throw new IOException("Error reading pidGen table from db: " + sqle.getMessage());
+ LOG.warn("Unable to read pidGen table; assuming it "
+ + "will be created shortly");
} finally {
try {
if (results!=null) results.close();
if (s!= null) s.close();
if (conn!=null) m_connectionPool.free(conn);
} catch (SQLException sqle2) {
LOG.warn("Error trying to free db "
+ "resources in DBPIDGenerator", sqle2);
} finally {
results=null;
s=null;
}
}
upgradeIfNeeded(oldPidGenDir);
}
/**
* Read the highest value from the old pidGen directory if it exists,
* and ensure it is never used.
*/
private void upgradeIfNeeded(File oldPidGenDir)
throws IOException {
if (oldPidGenDir!=null && oldPidGenDir.isDirectory()) {
String[] names=oldPidGenDir.list();
Arrays.sort(names);
if (names.length>0) {
BufferedReader in=new BufferedReader(
new InputStreamReader(
new FileInputStream(
new File(oldPidGenDir,
names[names.length-1]))));
String lastLine=null;
String line;
while ((line=in.readLine())!=null) {
lastLine=line;
}
in.close();
if (lastLine!=null) {
String[] parts=lastLine.split("|");
if (parts.length==2) {
neverGeneratePID(parts[0]);
}
}
}
}
}
/**
* Generate a new pid that is guaranteed to be unique, within the
* given namespace.
*/
public synchronized PID generatePID(String namespace) throws IOException {
int i=getHighestID(namespace);
i++;
setHighestID(namespace, i);
try {
m_lastPID = new PID(namespace + ":" + i);
} catch (MalformedPIDException e) {
throw new IOException(e.getMessage());
}
return m_lastPID;
}
/**
* Get the last pid that was generated.
*/
public synchronized PID getLastPID() {
return m_lastPID;
}
/**
* Cause the given PID to never be generated by the PID generator.
*/
public synchronized void neverGeneratePID(String pid)
throws IOException {
try {
PID p = new PID(pid);
String ns = p.getNamespaceId();
int id = Integer.parseInt(p.getObjectId());
if (id > getHighestID(ns)) {
setHighestID(ns, id);
}
} catch (MalformedPIDException mpe) {
throw new IOException(mpe.getMessage());
} catch (NumberFormatException nfe) {
// if the id part is not numeric, we already know we'll
// never generate that id because all generated ids are numeric.
}
}
/**
* Gets the highest id ever used for the given namespace.
*/
private int getHighestID(String namespace) {
Integer i=(Integer) m_highestID.get(namespace);
if (i==null) return 0;
return i.intValue();
}
/**
* Sets the highest id ever used for the given namespace.
*/
private void setHighestID(String namespace, int id)
throws IOException {
m_highestID.put(namespace, new Integer(id));
// write the new highest id in the database, too
Connection conn=null;
try {
conn=m_connectionPool.getConnection();
SQLUtility.replaceInto(conn,
"pidGen",
new String[] {"namespace", "highestID"},
new String[] {namespace, "" + id},
"namespace",
new boolean[] {false, true});
} catch (SQLException sqle) {
throw new IOException("Error setting highest id for "
+ "namespace in db: " + sqle.getMessage());
} finally {
if (conn!=null) {
m_connectionPool.free(conn);
}
}
}
}
| true | true | public DBPIDGenerator(ConnectionPool cPool, File oldPidGenDir)
throws IOException {
m_connectionPool=cPool;
m_highestID=new HashMap();
// load the values from the database into the m_highestID hash
// pidGen: namespace highestID
Statement s=null;
ResultSet results=null;
Connection conn=null;
try {
conn=m_connectionPool.getConnection();
String query="SELECT namespace, highestID FROM pidGen";
s=conn.createStatement();
results=s.executeQuery(query);
while (results.next()) {
m_highestID.put(results.getString("namespace"),
new Integer(results.getInt("highestID")));
}
} catch (SQLException sqle) {
throw new IOException("Error reading pidGen table from db: " + sqle.getMessage());
} finally {
try {
if (results!=null) results.close();
if (s!= null) s.close();
if (conn!=null) m_connectionPool.free(conn);
} catch (SQLException sqle2) {
LOG.warn("Error trying to free db "
+ "resources in DBPIDGenerator", sqle2);
} finally {
results=null;
s=null;
}
}
upgradeIfNeeded(oldPidGenDir);
}
| public DBPIDGenerator(ConnectionPool cPool, File oldPidGenDir)
throws IOException {
m_connectionPool=cPool;
m_highestID=new HashMap();
// load the values from the database into the m_highestID hash
// pidGen: namespace highestID
Statement s=null;
ResultSet results=null;
Connection conn=null;
try {
conn=m_connectionPool.getConnection();
String query="SELECT namespace, highestID FROM pidGen";
s=conn.createStatement();
results=s.executeQuery(query);
while (results.next()) {
m_highestID.put(results.getString("namespace"),
new Integer(results.getInt("highestID")));
}
} catch (SQLException sqle) {
LOG.warn("Unable to read pidGen table; assuming it "
+ "will be created shortly");
} finally {
try {
if (results!=null) results.close();
if (s!= null) s.close();
if (conn!=null) m_connectionPool.free(conn);
} catch (SQLException sqle2) {
LOG.warn("Error trying to free db "
+ "resources in DBPIDGenerator", sqle2);
} finally {
results=null;
s=null;
}
}
upgradeIfNeeded(oldPidGenDir);
}
|
diff --git a/Chat/src/Server/ServerReady.java b/Chat/src/Server/ServerReady.java
index fa518a6..1509f96 100644
--- a/Chat/src/Server/ServerReady.java
+++ b/Chat/src/Server/ServerReady.java
@@ -1,59 +1,61 @@
package Server;
import java.io.IOException;
import Communications.TCP;
import Messages.ClientRequestInfoMessage;
import Messages.ClientRequestUpdateMessage;
import Messages.ErrorMessage;
import Messages.LookupFailedMessage;
import Messages.Message;
import Messages.NameCollisionMessage;
import Messages.ServerConfirmationUpdateMessage;
import Messages.ServerSendsInfoMessage;
public class ServerReady extends ServerState{
public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) {
if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){
+ System.out.println("info message");
Message message = null;
String user=((ClientRequestInfoMessage)tcpMessage).targetUsername;
String ip=LookupTable.lookup(user);
if(ip==null){
message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user);
}
else{
message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){
+ System.out.println("update message");
Message message = null;
String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername;
String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP;
if(LookupTable.lookup(user)!=null){
message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user);
}
else{
LookupTable.bind(user, ip);
message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage!=null){
tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0]));
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
else if(System.currentTimeMillis()-timeEnteredState>300000){
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
return this;
}
}
| false | true | public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) {
if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){
Message message = null;
String user=((ClientRequestInfoMessage)tcpMessage).targetUsername;
String ip=LookupTable.lookup(user);
if(ip==null){
message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user);
}
else{
message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){
Message message = null;
String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername;
String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP;
if(LookupTable.lookup(user)!=null){
message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user);
}
else{
LookupTable.bind(user, ip);
message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage!=null){
tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0]));
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
else if(System.currentTimeMillis()-timeEnteredState>300000){
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
return this;
}
| public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) {
if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){
System.out.println("info message");
Message message = null;
String user=((ClientRequestInfoMessage)tcpMessage).targetUsername;
String ip=LookupTable.lookup(user);
if(ip==null){
message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user);
}
else{
message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){
System.out.println("update message");
Message message = null;
String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername;
String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP;
if(LookupTable.lookup(user)!=null){
message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user);
}
else{
LookupTable.bind(user, ip);
message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip);
}
tcp.send(message);
return this;
}
else if(tcpMessage!=null){
tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0]));
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
else if(System.currentTimeMillis()-timeEnteredState>300000){
try {
tcp.close();
} catch (IOException e) {}
return new ServerDisconnected();
}
return this;
}
|
diff --git a/test/samples/uscxml/applications/SpatialMapTicker.java b/test/samples/uscxml/applications/SpatialMapTicker.java
index 5ccb0a24..8d2a5f14 100644
--- a/test/samples/uscxml/applications/SpatialMapTicker.java
+++ b/test/samples/uscxml/applications/SpatialMapTicker.java
@@ -1,153 +1,153 @@
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.Random;
import org.umundo.core.Greeter;
import org.umundo.core.Message;
import org.umundo.core.Node;
import org.umundo.core.Publisher;
public class SpatialMapTicker {
Node node;
Publisher pub;
Greeter greeter;
ArrayList<Sensor> sensors = new ArrayList<Sensor>();
static ArrayList<SensorMessage> messages = new ArrayList<SensorMessage>();
static Random random = new Random(System.currentTimeMillis());
public class SensorMessage {
public String message;
public int severity;
public SensorMessage(String message, int severity) {
this.message = message;
this.severity = severity;
}
public SensorMessage(String message) {
this.message = message;
this.severity = 3;
}
}
public class Sensor {
@Override
public String toString() {
return "Sensor [id=" + id + ", lat=" + lat + ", lon=" + lon
+ ", html=" + getHTML() + "]";
}
public String id = "";
public Double lat = new Double(0);
public Double lon = new Double(0);
LinkedList<SensorMessage> messages = new LinkedList<SensorMessage>();
public void addMessage(SensorMessage message) {
if (messages.size() > 15)
messages.removeLast();
messages.addFirst(message);
}
public String getHTML() {
StringBuilder sb = new StringBuilder();
for (SensorMessage message : messages) {
sb.append(message.severity);
sb.append(": ");
sb.append(message.message);
sb.append("<br />");
}
return sb.toString();
}
}
public class SensorGreeter extends Greeter {
public void welcome(Publisher publisher, String nodeId, String subId) {
// send all sensors to new subscribers
for (Sensor sensor : sensors) {
Message msg = new Message(); //Message.toSubscriber(subId);
msg.putMeta("id", sensor.id);
msg.putMeta("lat", sensor.lat.toString());
msg.putMeta("lon", sensor.lon.toString());
msg.putMeta("html", sensor.getHTML());
pub.send(msg);
}
}
@Override
public void farewell(Publisher arg0, String nodeId, String subId) {
}
}
public SpatialMapTicker() {
node = new Node();
pub = new Publisher("map/tick");
greeter = new SensorGreeter();
pub.setGreeter(greeter);
node.addPublisher(pub);
double latCenter = 59.32;
double lonCenter = 18.08;
int nrSensors = 15; //(int) (Math.random() * 20);
for (int i = 0; i < nrSensors; i++) {
Sensor sensor = new Sensor();
double latOffset = (Math.random() - 0.5) * 0.3;
double lonOffset = (Math.random() - 0.5) * 0.3;
sensor.id = "Sensor #" + i;
sensor.lat = latCenter + latOffset;
sensor.lon = lonCenter + lonOffset;
sensors.add(sensor);
}
}
public static void main(String[] args) {
SpatialMapTicker ticker = new SpatialMapTicker();
ticker.run();
}
private void run() {
messages.add(new SensorMessage("Oil pressure threshold exceeded"));
- messages.add(new SensorMessage("Error #245 in diagnostics unit"));
+ messages.add(new SensorMessage("Equipment is on fire"));
messages.add(new SensorMessage("Error #32 in diagnostics unit"));
- messages.add(new SensorMessage("Error #81 in diagnostics unit"));
- messages.add(new SensorMessage("Error #15 in diagnostics unit"));
+ messages.add(new SensorMessage("Unauthorized startup"));
+ messages.add(new SensorMessage("Tire pressure too low"));
messages.add(new SensorMessage("Error #145 in diagnostics unit"));
messages.add(new SensorMessage("Unit was moved out of construction site area"));
messages.add(new SensorMessage("Hydraulic pressure exceeding safety limits"));
messages.add(new SensorMessage("Drivers seat belts are not fastened!"));
messages.add(new SensorMessage("Battery recharge cycles exceeded"));
messages.add(new SensorMessage("Unit operated outside recommended paramters"));
while (true) {
try {
- Thread.sleep((long) (Math.random() * 1000) + 200);
+ Thread.sleep((long) (Math.random() * 300) + 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Sensor sensor = sensors.get(random.nextInt(sensors.size()));
SensorMessage fault = messages.get(random.nextInt(messages.size()));
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
String nowString = sdf.format(now);
sensor.addMessage(fault);
// System.out.println("Publishing " + sensor);
Message msg = new Message();
msg.putMeta("id", sensor.id);
msg.putMeta("lat", sensor.lat.toString());
msg.putMeta("lon", sensor.lon.toString());
msg.putMeta("html", sensor.getHTML());
msg.putMeta("time", nowString);
msg.putMeta("timeStamp", Long.toString(now.getTime()));
msg.putMeta("message", sensor.messages.getFirst().message);
msg.putMeta("severity", Integer.toString(random.nextInt(10)));
pub.send(msg);
}
}
}
| false | true | private void run() {
messages.add(new SensorMessage("Oil pressure threshold exceeded"));
messages.add(new SensorMessage("Error #245 in diagnostics unit"));
messages.add(new SensorMessage("Error #32 in diagnostics unit"));
messages.add(new SensorMessage("Error #81 in diagnostics unit"));
messages.add(new SensorMessage("Error #15 in diagnostics unit"));
messages.add(new SensorMessage("Error #145 in diagnostics unit"));
messages.add(new SensorMessage("Unit was moved out of construction site area"));
messages.add(new SensorMessage("Hydraulic pressure exceeding safety limits"));
messages.add(new SensorMessage("Drivers seat belts are not fastened!"));
messages.add(new SensorMessage("Battery recharge cycles exceeded"));
messages.add(new SensorMessage("Unit operated outside recommended paramters"));
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000) + 200);
} catch (InterruptedException e) {
e.printStackTrace();
}
Sensor sensor = sensors.get(random.nextInt(sensors.size()));
SensorMessage fault = messages.get(random.nextInt(messages.size()));
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
String nowString = sdf.format(now);
sensor.addMessage(fault);
// System.out.println("Publishing " + sensor);
Message msg = new Message();
msg.putMeta("id", sensor.id);
msg.putMeta("lat", sensor.lat.toString());
msg.putMeta("lon", sensor.lon.toString());
msg.putMeta("html", sensor.getHTML());
msg.putMeta("time", nowString);
msg.putMeta("timeStamp", Long.toString(now.getTime()));
msg.putMeta("message", sensor.messages.getFirst().message);
msg.putMeta("severity", Integer.toString(random.nextInt(10)));
pub.send(msg);
}
}
| private void run() {
messages.add(new SensorMessage("Oil pressure threshold exceeded"));
messages.add(new SensorMessage("Equipment is on fire"));
messages.add(new SensorMessage("Error #32 in diagnostics unit"));
messages.add(new SensorMessage("Unauthorized startup"));
messages.add(new SensorMessage("Tire pressure too low"));
messages.add(new SensorMessage("Error #145 in diagnostics unit"));
messages.add(new SensorMessage("Unit was moved out of construction site area"));
messages.add(new SensorMessage("Hydraulic pressure exceeding safety limits"));
messages.add(new SensorMessage("Drivers seat belts are not fastened!"));
messages.add(new SensorMessage("Battery recharge cycles exceeded"));
messages.add(new SensorMessage("Unit operated outside recommended paramters"));
while (true) {
try {
Thread.sleep((long) (Math.random() * 300) + 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Sensor sensor = sensors.get(random.nextInt(sensors.size()));
SensorMessage fault = messages.get(random.nextInt(messages.size()));
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
String nowString = sdf.format(now);
sensor.addMessage(fault);
// System.out.println("Publishing " + sensor);
Message msg = new Message();
msg.putMeta("id", sensor.id);
msg.putMeta("lat", sensor.lat.toString());
msg.putMeta("lon", sensor.lon.toString());
msg.putMeta("html", sensor.getHTML());
msg.putMeta("time", nowString);
msg.putMeta("timeStamp", Long.toString(now.getTime()));
msg.putMeta("message", sensor.messages.getFirst().message);
msg.putMeta("severity", Integer.toString(random.nextInt(10)));
pub.send(msg);
}
}
|
diff --git a/src/main/java/cukepresentation/HelloWorldWebServer.java b/src/main/java/cukepresentation/HelloWorldWebServer.java
index cc72587..d5cd5fd 100644
--- a/src/main/java/cukepresentation/HelloWorldWebServer.java
+++ b/src/main/java/cukepresentation/HelloWorldWebServer.java
@@ -1,31 +1,31 @@
package cukepresentation;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* @author: Stephen Abrams
*/
public class HelloWorldWebServer {
private HttpServer server;
int port;
public HelloWorldWebServer(int port) {
this.port = port;
}
public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(this.port), 0);
- server.createContext("/hello_world", new HelloWorldHandler());
+ server.createContext("/hello", new HelloWorldHandler());
server.setExecutor(null);
server.start();
}
public void stop() {
if (server != null)
server.stop(0);
}
}
| true | true | public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(this.port), 0);
server.createContext("/hello_world", new HelloWorldHandler());
server.setExecutor(null);
server.start();
}
| public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(this.port), 0);
server.createContext("/hello", new HelloWorldHandler());
server.setExecutor(null);
server.start();
}
|
diff --git a/src/edu/nrao/dss/client/Reservations.java b/src/edu/nrao/dss/client/Reservations.java
index 91ee30a..c2cde98 100644
--- a/src/edu/nrao/dss/client/Reservations.java
+++ b/src/edu/nrao/dss/client/Reservations.java
@@ -1,41 +1,41 @@
package edu.nrao.dss.client;
import java.util.Date;
import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.http.client.RequestBuilder;
public class Reservations extends ContentPanel {
public ReservationsGrid res;
public Reservations (Date start, int days) {
super();
initLayout(start, days);
}
private void initLayout(Date start, int days){
- setHeading("Reservatons");
+ setHeading("Reservations");
setBorders(true);
// put the reservation grid inside
FitLayout fl = new FitLayout();
setLayout(fl);
res = new ReservationsGrid(start, days);
add(res, new FitData(10));
}
public void update(String start, String days) {
// get the period explorer to load these
String url = "/reservations?start=" + start + "&days=" + days;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
DynamicHttpProxy<BaseListLoadResult<BaseModelData>> proxy = res.getProxy();
proxy.setBuilder(builder);
res.load();
}
}
| true | true | private void initLayout(Date start, int days){
setHeading("Reservatons");
setBorders(true);
// put the reservation grid inside
FitLayout fl = new FitLayout();
setLayout(fl);
res = new ReservationsGrid(start, days);
add(res, new FitData(10));
}
| private void initLayout(Date start, int days){
setHeading("Reservations");
setBorders(true);
// put the reservation grid inside
FitLayout fl = new FitLayout();
setLayout(fl);
res = new ReservationsGrid(start, days);
add(res, new FitData(10));
}
|
diff --git a/ace-deployment-streamgenerator/src/test/java/org/apache/ace/deployment/streamgenerator/impl/StreamTest.java b/ace-deployment-streamgenerator/src/test/java/org/apache/ace/deployment/streamgenerator/impl/StreamTest.java
index bdc6e7cd..05821fce 100644
--- a/ace-deployment-streamgenerator/src/test/java/org/apache/ace/deployment/streamgenerator/impl/StreamTest.java
+++ b/ace-deployment-streamgenerator/src/test/java/org/apache/ace/deployment/streamgenerator/impl/StreamTest.java
@@ -1,314 +1,314 @@
/*
* 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.ace.deployment.streamgenerator.impl;
import static org.apache.ace.test.utils.TestUtils.BROKEN;
import static org.apache.ace.test.utils.TestUtils.UNIT;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import org.apache.ace.deployment.provider.DeploymentProvider;
import org.apache.ace.test.constants.TestConstants;
import org.apache.ace.test.utils.TestUtils;
import org.apache.ace.test.utils.deployment.TestProvider;
import org.osgi.service.log.LogService;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.*;
/**
* Unit tests for the deployment admin stream.
*/
public class StreamTest {
private static final int COPY_BUFFER_SIZE = 4096;
private StreamGeneratorImpl m_generator;
private TestProvider m_provider;
@BeforeTest(alwaysRun = true)
protected void setUp() throws Exception {
m_generator = new StreamGeneratorImpl();
m_provider = new TestProvider();
InputStream is = newBundle().build(); // TODO this is a very trivial bundle, put more data in?
File temp = File.createTempFile("bundle", "jar");
temp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(temp);
byte[] buf = new byte[4096];
int b = is.read(buf);
while (b != -1) {
fos.write(buf, 0, b);
b = is.read(buf);
}
fos.close();
is.close();
URL url = temp.toURI().toURL();
m_provider.addData("A1.jar", "A1", url, "1.0.0", true);
m_provider.addData("A2.jar", "A2", url, "1.0.0", false);
m_provider.addData("A3.jar", "A3", url, "1.0.0", true);
TestUtils.configureObject(m_generator, DeploymentProvider.class, m_provider);
TestUtils.configureObject(m_generator, LogService.class);
}
public static void main(String[] args) {
final InputStream[] streams = new InputStream[300];
for (int i = 1; i <= 250; i++) {
- final String id = "gateway-" + i;
+ final String id = "target-" + i;
try {
streams[i - 1] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/" + id + "/versions/1.0.0").openStream();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 0; i < 50; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(1);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 50; i < 100; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(2);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 100; i < 150; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(3);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 150; i < 200; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(4);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 200; i < 250; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 250; i < 300; i++) {
try {
if (streams[i] == null) {
- streams[i] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/gateway-" + (i + 1) + "/versions/1.0.0").openStream();
+ streams[i] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/target-" + (i + 1) + "/versions/1.0.0").openStream();
}
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
}
/**
* The specification requires the stream to be readable by JarInputStream (114.3) so make sure it is.
*/
@Test(groups = { UNIT })
public void isJarInputStreamReadable() throws Exception {
isJarInputStreamReadable(new JarInputStream(m_generator.getDeploymentPackage("test", "1.0.0")), false);
isJarInputStreamReadable(new JarInputStream(m_generator.getDeploymentPackage("test", "0.0.0", "1.0.0")), true);
}
private void isJarInputStreamReadable(JarInputStream jis, boolean fixPackage) throws Exception {
assert jis != null : "We should have got an input stream for this deployment package.";
Manifest m = jis.getManifest();
assert m != null : "The stream should contain a valid manifest.";
Attributes att = m.getMainAttributes();
assert att.getValue("DeploymentPackage-SymbolicName").equals("test");
assert att.getValue("DeploymentPackage-Version").equals("1.0.0");
assert (fixPackage && att.getValue("DeploymentPackage-FixPack").equals("[0.0.0,1.0.0)")) || (att.getValue("DeploymentPackage-FixPack") == null);
HashSet<String> names = new HashSet<String>();
JarEntry e = jis.getNextJarEntry();
while (e != null) {
String name = e.getName();
names.add(name);
if (fixPackage && name.equals("A2.jar")) {
assert e.getAttributes().getValue("DeploymentPackage-Missing").equals("true");
}
// we could check the name here against the manifest
// and make sure we actually get what was promised
Attributes a = m.getAttributes(name);
assert a != null : "The stream should contain a named section for " + name + " in the manifest.";
byte[] buffer = new byte[COPY_BUFFER_SIZE];
int bytes = jis.read(buffer);
long size = 0;
while (bytes != -1) {
size += bytes;
bytes = jis.read(buffer);
}
// get the next entry, if any
e = jis.getNextJarEntry();
}
if (!fixPackage) {
assert names.size() == 3 : "The stream should have contained three resources.";
}
else {
assert names.size() == 2 : "The stream should have contained three resources";
}
assert names.contains("A1.jar") : "The stream should have contained a resource called A1.jar";
assert fixPackage ^ names.contains("A2.jar") : "The stream should have contained a resource called A2.jar";
assert names.contains("A3.jar") : "The stream should have contained a resource called A3.jar";
}
/**
* Test reading 100 streams sequentially.
*/
@Test(groups = { UNIT, BROKEN })
public void hundredStreamsSequentially() throws Exception {
for (int i = 0; i < 100; i++) {
isJarInputStreamReadable();
}
}
private Exception m_failure;
/**
* Test reading 100 streams concurrently.
*/
@Test(groups = { UNIT, BROKEN }) // marked broken after discussing it with Karl
public void hundredStreamsConcurrently() throws Exception {
ExecutorService e = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
e.execute(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
isJarInputStreamReadable();
}
catch (Exception e) {
m_failure = e;
}
}
}
});
}
e.shutdown();
e.awaitTermination(10, TimeUnit.SECONDS);
assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();
}
}
| false | true | public static void main(String[] args) {
final InputStream[] streams = new InputStream[300];
for (int i = 1; i <= 250; i++) {
final String id = "gateway-" + i;
try {
streams[i - 1] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/" + id + "/versions/1.0.0").openStream();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 0; i < 50; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(1);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 50; i < 100; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(2);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 100; i < 150; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(3);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 150; i < 200; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(4);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 200; i < 250; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 250; i < 300; i++) {
try {
if (streams[i] == null) {
streams[i] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/gateway-" + (i + 1) + "/versions/1.0.0").openStream();
}
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
}
| public static void main(String[] args) {
final InputStream[] streams = new InputStream[300];
for (int i = 1; i <= 250; i++) {
final String id = "target-" + i;
try {
streams[i - 1] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/" + id + "/versions/1.0.0").openStream();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 0; i < 50; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(1);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 50; i < 100; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(2);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 100; i < 150; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(3);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 150; i < 200; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(4);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 200; i < 250; i++) {
try {
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
@Override
public void run() {
int done = 0;
while (done < 50) {
for (int i = 250; i < 300; i++) {
try {
if (streams[i] == null) {
streams[i] = new URL("http://127.0.0.1:" + TestConstants.PORT + "/data/target-" + (i + 1) + "/versions/1.0.0").openStream();
}
int in = streams[i].read();
if (in == -1) {
System.out.println(5);
done++;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
}
|
diff --git a/bundles/org.eclipse.e4.tools.emf.liveeditor/src/org/eclipse/e4/tools/emf/liveeditor/OpenLiveDialogHandler.java b/bundles/org.eclipse.e4.tools.emf.liveeditor/src/org/eclipse/e4/tools/emf/liveeditor/OpenLiveDialogHandler.java
index 630ae811..27c6321d 100644
--- a/bundles/org.eclipse.e4.tools.emf.liveeditor/src/org/eclipse/e4/tools/emf/liveeditor/OpenLiveDialogHandler.java
+++ b/bundles/org.eclipse.e4.tools.emf.liveeditor/src/org/eclipse/e4/tools/emf/liveeditor/OpenLiveDialogHandler.java
@@ -1,72 +1,73 @@
/*******************************************************************************
* Copyright (c) 2010 BestSolution.at 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:
* Tom Schindl <[email protected]> - initial API and implementation
******************************************************************************/
package org.eclipse.e4.tools.emf.liveeditor;
import javax.inject.Named;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.tools.emf.ui.common.IModelResource;
import org.eclipse.e4.tools.emf.ui.internal.wbm.ApplicationModelEditor;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.services.IStylingEngine;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
public class OpenLiveDialogHandler {
private Shell shell;
public OpenLiveDialogHandler() {
System.err.println("Created Live Dialog Handler");
}
@Execute
- public void run(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
- IEclipseContext context, MApplication application, IStylingEngine engine) {
- if (this.shell == null || ! this.shell.isDisposed()) {
+ public void run(@Named(IServiceConstants.ACTIVE_SHELL) Shell s,
+ IEclipseContext c, MApplication application, IStylingEngine engine) {
+ if (this.shell == null || this.shell.isDisposed()) {
try {
- shell = new Shell(shell.getDisplay(),SWT.ON_TOP|SWT.SHELL_TRIM);
+ this.shell = new Shell(s.getDisplay(),SWT.ON_TOP|SWT.SHELL_TRIM);
//FIXME Style
- shell.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ this.shell.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
FillLayout layout = new FillLayout();
layout.marginHeight=10;
layout.marginWidth=10;
- shell.setLayout(layout);
- final IEclipseContext childContext = context
+ this.shell.setLayout(layout);
+ final IEclipseContext childContext = c
.createChild("EditorContext");
MemoryModelResource resource = new MemoryModelResource(application);
childContext.set(IModelResource.class, resource);
childContext.set(Composite.class.getName(), shell);
childContext.set(IModelResource.class, resource);
ContextInjectionFactory.make(ApplicationModelEditor.class, childContext);
// new ApplicationModelEditor(shell, childContext, resource, null);
shell.open();
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
childContext.dispose();
+ shell = null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| false | true | public void run(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
IEclipseContext context, MApplication application, IStylingEngine engine) {
if (this.shell == null || ! this.shell.isDisposed()) {
try {
shell = new Shell(shell.getDisplay(),SWT.ON_TOP|SWT.SHELL_TRIM);
//FIXME Style
shell.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
FillLayout layout = new FillLayout();
layout.marginHeight=10;
layout.marginWidth=10;
shell.setLayout(layout);
final IEclipseContext childContext = context
.createChild("EditorContext");
MemoryModelResource resource = new MemoryModelResource(application);
childContext.set(IModelResource.class, resource);
childContext.set(Composite.class.getName(), shell);
childContext.set(IModelResource.class, resource);
ContextInjectionFactory.make(ApplicationModelEditor.class, childContext);
// new ApplicationModelEditor(shell, childContext, resource, null);
shell.open();
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
childContext.dispose();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| public void run(@Named(IServiceConstants.ACTIVE_SHELL) Shell s,
IEclipseContext c, MApplication application, IStylingEngine engine) {
if (this.shell == null || this.shell.isDisposed()) {
try {
this.shell = new Shell(s.getDisplay(),SWT.ON_TOP|SWT.SHELL_TRIM);
//FIXME Style
this.shell.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
FillLayout layout = new FillLayout();
layout.marginHeight=10;
layout.marginWidth=10;
this.shell.setLayout(layout);
final IEclipseContext childContext = c
.createChild("EditorContext");
MemoryModelResource resource = new MemoryModelResource(application);
childContext.set(IModelResource.class, resource);
childContext.set(Composite.class.getName(), shell);
childContext.set(IModelResource.class, resource);
ContextInjectionFactory.make(ApplicationModelEditor.class, childContext);
// new ApplicationModelEditor(shell, childContext, resource, null);
shell.open();
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
childContext.dispose();
shell = null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/src/main/java/net/nexisonline/spade/SpadeWorldListener.java b/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
index 516cef8..db2c207 100644
--- a/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
+++ b/src/main/java/net/nexisonline/spade/SpadeWorldListener.java
@@ -1,186 +1,188 @@
package net.nexisonline.spade;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import net.nexisonline.spade.populators.DungeonPopulator;
import org.bukkit.World;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.generator.BlockPopulator;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.reader.UnicodeReader;
public class SpadeWorldListener extends WorldListener {
private SpadePlugin spade;
private Collection<String> worlds;
private Map<String, Object> root;
private Yaml yaml;
public SpadeWorldListener(SpadePlugin plugin) {
spade = plugin;
}
@Override
public void onChunkLoad(ChunkLoadEvent e) {
for (BlockPopulator bp : e.getWorld().getPopulators()) {
if (bp instanceof DungeonPopulator) {
((DungeonPopulator) bp).onChunkLoad(e.getChunk().getX(), e.getChunk().getZ());
}
}
}
@Override
public void onWorldLoad(WorldLoadEvent e) {
}
@Override
public void onWorldSave(WorldSaveEvent e) {
saveWorlds();
}
@SuppressWarnings("unchecked")
private void load() {
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(options);
FileInputStream stream = null;
File file = new File(spade.getDataFolder(), "Spade.yml");
if(!file.exists())
return;
try {
stream = new FileInputStream(file);
root=(Map<String,Object>)yaml.load(new UnicodeReader(stream));
} catch (IOException e) {
root = new HashMap<String, Object>();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {}
}
}
@SuppressWarnings("unchecked")
public void loadWorlds() {
load();
Object co = null;
if(root!=null && root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
- Map<String,Object> worldMap = (Map<String, Object>) root.get("worlds");
+ Map<String,Object> worldMap = (Map<String, Object>) co;
worlds = worldMap.keySet();
+ SpadeLogging.info("Loaded worlds:");
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
+ SpadeLogging.info(" + "+worldName+" (cp: "+(String)chunkProvider.get("name")+")");
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = root = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
private void save() {
FileOutputStream stream = null;
File file = new File(spade.getDataFolder(), "Spade.yml");
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
try {
stream = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
writer.append("\r\n# Spade Terrain Generator Plugin");
writer.append("\r\n# Configuration File");
writer.append("\r\n# ");
writer.append("\r\n# AUTOMATICALLY GENERATED");
writer.append("\r\n");
yaml.dump(root, writer);
return;
} catch (IOException e) {} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {}
}
return;
}
public void saveWorlds() {
root.clear();
Map<String,Object> worlds = new HashMap<String,Object>();
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
if (w.getGenerator() instanceof SpadeChunkProvider) {
SpadeChunkProvider cp = (SpadeChunkProvider) w.getGenerator();
chunkProvider.put("name", spade.getNameForClass(cp));
chunkProvider.put("config", cp.getConfig());
} else {
chunkProvider.put("name", "stock");
}
world.put("chunk-provider",chunkProvider);
}
{
spade.genLimits.get(worldName.toLowerCase());
world.put("limits", (new GenerationLimits()).getConfig());
}
worlds.put(worldName, world);
}
root.put("worlds", worlds);
save();
}
}
| false | true | public void loadWorlds() {
load();
Object co = null;
if(root!=null && root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
Map<String,Object> worldMap = (Map<String, Object>) root.get("worlds");
worlds = worldMap.keySet();
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = root = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
| public void loadWorlds() {
load();
Object co = null;
if(root!=null && root.containsKey("worlds")) {
co = root.get("worlds");
if(co instanceof Map<?,?>) {
Map<String,Object> worldMap = (Map<String, Object>) co;
worlds = worldMap.keySet();
SpadeLogging.info("Loaded worlds:");
for (String worldName : this.worlds) {
Map<String,Object> currWorld = (Map<String, Object>) worldMap.get(worldName);
Map<String,Object> limits = (Map<String, Object>) currWorld.get("limits");
Long seed = (Long) ((currWorld.get("seed")==null)?((new Random()).nextLong()):currWorld.get("seed"));
spade.genLimits.put(worldName.toLowerCase(), new GenerationLimits(limits));
Map<String,Object> chunkManager = (Map<String, Object>) currWorld.get("chunk-manager");
if(chunkManager == null) {
chunkManager = new HashMap<String,Object>();
chunkManager.put("name", "stock");
}
Map<String,Object> chunkProvider = (Map<String, Object>) currWorld.get("chunk-provider");
if(chunkProvider == null) {
chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
}
SpadeLogging.info(" + "+worldName+" (cp: "+(String)chunkProvider.get("name")+")");
spade.loadWorld(worldName, seed, (String)chunkManager.get("name"), (String)chunkProvider.get("name"), (Map<String,Object>)chunkProvider.get("config"));
}
}
} else {
for (World w : spade.getServer().getWorlds()) {
String worldName = w.getName();
Map<String,Object> world = root = new HashMap<String,Object>();
{
Map<String,Object> chunkProvider = new HashMap<String,Object>();
chunkProvider.put("name", "stock");
chunkProvider.put("config", null);
world.put("chunk-provider",chunkProvider);
}
{
world.put("limits", (new GenerationLimits()).getConfig());
}
root.put(worldName, world);
}
save();
}
}
|
diff --git a/src/main/com/iappsam/search/SupplierSearcher.java b/src/main/com/iappsam/search/SupplierSearcher.java
index d71f261..d0a0759 100644
--- a/src/main/com/iappsam/search/SupplierSearcher.java
+++ b/src/main/com/iappsam/search/SupplierSearcher.java
@@ -1,10 +1,10 @@
package com.iappsam.search;
import com.iappsam.Supplier;
public class SupplierSearcher extends AbstractSearcher<Supplier> {
public SupplierSearcher() {
- super(Supplier.class, "person.name", "address", "contactPerson.person.name");
+ super(Supplier.class, "name", "address", "contactPerson.person.name");
}
}
| true | true | public SupplierSearcher() {
super(Supplier.class, "person.name", "address", "contactPerson.person.name");
}
| public SupplierSearcher() {
super(Supplier.class, "name", "address", "contactPerson.person.name");
}
|
diff --git a/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java b/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java
index d323dd14..3fe1e0da 100644
--- a/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java
+++ b/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java
@@ -1,1347 +1,1349 @@
/**********************************************************************************
*
* $Header:
*
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006, 2007 Foothill College, ETUDES 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 org.sakaiproject.component.app.melete;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.URLDecoder;
import org.sakaiproject.api.app.melete.MeleteCHService;
import org.sakaiproject.api.app.melete.MeleteSecurityService;
import org.sakaiproject.component.app.melete.MeleteUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.melete.exception.MeleteException;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.entity.api.Reference;
/*
* Created on Sep 18, 2006 by rashmi
*
* This is a basic class to do all content hosting service work through melete
* Rashmi - 12/8/06 - add checks for upload img being greater than 1Mb
* Rashmi - 12/16/06 - fck editor upload image goes to melete collection and not resources.
* Rashmi - 1/16/07 - remove word inserted comments
* Mallika - 1/29/06 - Needed to add some new code to add url for embedded images
* Rashmi - changed logic to get list of images and url
* Rashmi - 2/12/07 - add alternate reference property at collection level too
* Rashmi - 3/6/07 - revised display name of modules collection with no slashes
* Rashmi - 5/9/07 - revised iteration to get listoflinks
* Mallika - 5/31/07 - added Validator
* Mallika - 6/4/07 - Added two new methods (copyIntoFolder,getCollection)
* Mallika - 6/4/07 - Added logic to check for resource in findlocal
*/
public class MeleteCHServiceImpl implements MeleteCHService {
/** Dependency: The logging service. */
public Log logger = LogFactory.getLog(MeleteCHServiceImpl.class);
private ContentHostingService contentservice;
private static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = 100;
private SectionDB sectiondb;
/** Dependency: The Melete Security service. */
private MeleteSecurityService meleteSecurityService;
protected MeleteUtil meleteUtil = new MeleteUtil();
/** This string starts the references to resources in this service. */
static final String REFERENCE_ROOT = Entity.SEPARATOR+"meleteDocs";
/**
* Check if the current user has permission as author.
* @return true if the current user has permission to perform this action, false if not.
*/
public boolean isUserAuthor()throws Exception{
try {
return meleteSecurityService.allowAuthor();
} catch (Exception e) {
throw e;
}
}
public boolean isUserStudent()throws Exception{
try {
return meleteSecurityService.allowStudent();
} catch (Exception e) {
throw e;
}
}
private String addMeleteRootCollection(String rootCollectionRef, String collectionName, String description)
{
try
{
// Check to see if meleteDocs exists
ContentCollection collection = getContentservice().getCollection(rootCollectionRef);
return collection.getId();
}
catch (IdUnusedException e)
{
//if not, create it
if (logger.isDebugEnabled()) logger.debug("creating melete root collection "+rootCollectionRef);
ContentCollectionEdit edit = null;
try
{
edit = getContentservice().addCollection(rootCollectionRef);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, collectionName);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, description);
props.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT);
getContentservice().commitCollection(edit);
return edit.getId();
}
catch (Exception e2)
{
if(edit != null) getContentservice().cancelCollection(edit);
logger.warn("creating melete root collection: " + e2.toString());
}
}
catch (Exception e)
{
logger.warn("checking melete root collection: " + e.toString());
}
return null;
}
/*
*
*/
public String addCollectionToMeleteCollection(String meleteItemColl,String CollName)
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
// check if the root collection is available
String rootCollectionRef = Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR;
//Check to see if meleteDocs exists
String rootMeleteCollId = addMeleteRootCollection(rootCollectionRef, "meleteDocs", "root collection");
// now sub collection for course
String meleteItemDirCollId = rootMeleteCollId + meleteItemColl+ Entity.SEPARATOR;
String subMeleteCollId = addMeleteRootCollection(meleteItemDirCollId, CollName, "module collection");
return subMeleteCollId;
}
catch(Exception ex)
{
logger.error("error while creating modules collection" + ex.toString());
}
}
catch (Throwable t)
{
logger.warn("init(): ", t);
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
/*
*
*/
public String getCollectionId( String contentType,Integer modId )
{
String addToCollection ="";
String collName ="";
if(contentType.equals("typeEditor")){
addToCollection=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"module_"+ modId;
collName = "module_"+ modId;
}
else {
if (ToolManager.getCurrentPlacement()!=null)
addToCollection=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"uploads";
else
addToCollection=getMeleteSecurityService().getMeleteImportService().getDestinationContext()+Entity.SEPARATOR+"uploads";
collName = "uploads";
}
// check if collection exists otherwise create it
String addCollId = addCollectionToMeleteCollection(addToCollection,collName);
return addCollId;
}
/*
*
*/
public String getUploadCollectionId()
{
try{
String uploadCollectionId;
uploadCollectionId=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"uploads";
String collName = "uploads";
// check if collection exists
//read meletDocs dir name from web.xml
String uploadCollId = addCollectionToMeleteCollection(uploadCollectionId, collName);
return uploadCollId;
}catch(Exception e)
{
logger.error("error accessing uploads directory");
return null;
}
}
//Methods used by Migrate program - beginning
public String getCollectionId(String courseId, String contentType,Integer modId )
{
String addToCollection ="";
String collName ="";
if(contentType.equals("typeEditor")){
addToCollection=courseId+Entity.SEPARATOR+"module_"+ modId;
collName = "module_"+ modId;
}
else {
addToCollection=courseId+Entity.SEPARATOR+"uploads";
collName = "uploads";
}
// check if collection exists otherwise create it
String addCollId = addCollectionToMeleteCollection(addToCollection,collName);
return addCollId;
}
public String getUploadCollectionId(String courseId)
{
try{
String uploadCollectionId=courseId+Entity.SEPARATOR+"uploads";
String collName = "uploads";
// check if collection exists
//read meletDocs dir name from web.xml
String uploadCollId = addCollectionToMeleteCollection(uploadCollectionId, collName);
return uploadCollId;
}catch(Exception e)
{
logger.error("error accessing uploads directory");
return null;
}
}
// Methods used by Migrate program - End
/*
* for remote browser listing for sferyx editor just get the image files
**/
public List getListofImagesFromCollection(String collId)
{
try
{
// setup a security advisor
meleteSecurityService.pushAdvisor();
long starttime = System.currentTimeMillis();
logger.debug("time to get all collectionMap" + starttime);
ContentCollection c = getContentservice().getCollection(collId);
List mem = c.getMemberResources();
if (mem == null) return null;
ListIterator memIt = mem.listIterator();
while (memIt != null && memIt.hasNext())
{
ContentEntity ce = (ContentEntity) memIt.next();
if (ce.isResource())
{
String contentextension = ((ContentResource) ce).getProperties().getProperty(ce.getProperties().getNamePropContentType());
if (!contentextension.startsWith("image"))
{
memIt.remove();
}
}
else memIt.remove();
}
long endtime = System.currentTimeMillis();
logger.debug("end time to get all collectionMap" + (endtime - starttime));
return mem;
}
catch (Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
public List getListofFilesFromCollection(String collId)
{
try
{
// setup a security advisor
meleteSecurityService.pushAdvisor();
long starttime = System.currentTimeMillis();
logger.debug("time to get all collectionMap" + starttime);
ContentCollection c= getContentservice().getCollection(collId);
List mem = c.getMemberResources();
if (mem == null) return null;
ListIterator memIt = mem.listIterator();
while(memIt !=null && memIt.hasNext())
{
ContentEntity ce = (ContentEntity)memIt.next();
if (ce.isResource())
{
String contentextension = ((ContentResource)ce).getContentType();
if(contentextension.equals(MIME_TYPE_LINK) || contentextension.equals(MIME_TYPE_EDITOR))
{
memIt.remove();
}
} else memIt.remove();
}
long endtime = System.currentTimeMillis();
logger.debug("end time to get all collectionMap" + (endtime - starttime));
return mem;
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
/*
* for remote link browser listing for sferyx editor
* just get the urls and links and not image files
*/
public List getListofLinksFromCollection(String collId)
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
ContentCollection c= getContentservice().getCollection(collId);
List mem = c.getMemberResources();
if (mem == null) return null;
ListIterator memIt = mem.listIterator();
while(memIt !=null && memIt.hasNext())
{
ContentEntity ce = (ContentEntity)memIt.next();
if (ce.isResource())
{
String contentextension = ((ContentResource)ce).getContentType();
if(!contentextension.equals(MIME_TYPE_LINK))
memIt.remove();
}else memIt.remove();
}
return mem;
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
public List getListofMediaFromCollection(String collId)
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
ContentCollection c= getContentservice().getCollection(collId);
List mem = c.getMemberResources();
if (mem == null) return null;
ListIterator memIt = mem.listIterator();
while(memIt !=null && memIt.hasNext())
{
ContentEntity ce = (ContentEntity)memIt.next();
if (ce.isResource())
{
String contentextension = ((ContentResource)ce).getContentType();
if(contentextension.equals(MIME_TYPE_EDITOR))
memIt.remove();
}else memIt.remove();
}
return mem;
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
/*
*
*/
public ResourcePropertiesEdit fillInSectionResourceProperties(boolean encodingFlag,String secResourceName, String secResourceDescription)
{
ResourcePropertiesEdit resProperties = getContentservice().newResourceProperties();
// resProperties.addProperty (ResourceProperties.PROP_COPYRIGHT,);
// resourceProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE,);
//Glenn said to not set the two properties below
// resProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_ALERT,Boolean.TRUE.toString());
//resProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION,Boolean.FALSE.toString());
resProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, secResourceName);
resProperties.addProperty(ResourceProperties.PROP_DESCRIPTION, secResourceDescription);
resProperties.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT);
//Glenn said the property below may not need to be set either, will leave it in
//unless it creates problems
if (encodingFlag)
resProperties.addProperty(ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
return resProperties;
}
/*
* resource properties for images embedded in the editor content
*/
public ResourcePropertiesEdit fillEmbeddedImagesResourceProperties(String name)
{
ResourcePropertiesEdit resProperties = getContentservice().newResourceProperties();
//Glenn said to not set the two properties below
//resProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_ALERT,Boolean.TRUE.toString());
//resProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION,Boolean.FALSE.toString());
resProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
resProperties.addProperty(ResourceProperties.PROP_DESCRIPTION,"embedded image");
resProperties.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT);
return resProperties;
}
/*
*
*/
public void editResourceProperties(String selResourceIdFromList, String secResourceName, String secResourceDescription)
{
if(selResourceIdFromList == null || selResourceIdFromList.length() == 0) return;
ContentResourceEdit edit = null;
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
selResourceIdFromList = URLDecoder.decode(selResourceIdFromList,"UTF-8");
edit = getContentservice().editResource(selResourceIdFromList);
ResourcePropertiesEdit rp = edit.getPropertiesEdit();
rp.clear();
rp.addProperty(ResourceProperties.PROP_DISPLAY_NAME,secResourceName);
rp.addProperty(ResourceProperties.PROP_DESCRIPTION,secResourceDescription);
rp.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT);
getContentservice().commitResource(edit);
edit = null;
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
if(edit != null) getContentservice().cancelResource(edit);
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return;
}
public String addResourceItem(String name, String res_mime_type,String addCollId, byte[] secContentData, ResourcePropertiesEdit res ) throws Exception
{
ContentResource resource = null;
name = URLDecoder.decode(name,"UTF-8");
if (logger.isDebugEnabled()) logger.debug("IN addResourceItem "+name+" addCollId "+addCollId);
// need to add notify logic here and set the arg6 accordingly.
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to add resource");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
String finalName = addCollId + name;
if (finalName.length() > getContentservice().MAXIMUM_RESOURCE_ID_LENGTH)
{
// leaving room for CHS inserted duplicate filenames -1 -2 etc
int extraChars = finalName.length() - getContentservice().MAXIMUM_RESOURCE_ID_LENGTH + 3;
name = name.substring(0, name.length() - extraChars);
}
resource = getContentservice().addResource(name, addCollId, MAXIMUM_ATTEMPTS_FOR_UNIQUENESS, res_mime_type, secContentData, res, 0);
// check if its duplicate file and edit the resource name if it is
String checkDup = resource.getUrl().substring(resource.getUrl().lastIndexOf("/") + 1);
ContentResourceEdit edit = null;
try
{
if (!checkDup.equals(name))
{
edit = getContentservice().editResource(resource.getId());
ResourcePropertiesEdit rp = edit.getPropertiesEdit();
String desc = rp.getProperty(ResourceProperties.PROP_DESCRIPTION);
rp.clear();
rp.addProperty(ResourceProperties.PROP_DISPLAY_NAME, checkDup);
rp.addProperty(ResourceProperties.PROP_DESCRIPTION, desc);
rp.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT);
getContentservice().commitResource(edit);
edit = null;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (edit != null) getContentservice().cancelResource(edit);
}
}
catch(PermissionException e)
{
logger.error("permission is denied");
}
catch(IdInvalidException e)
{
logger.error("title" + " " + e.getMessage ());
throw new MeleteException("failed");
}
catch(IdLengthException e)
{
logger.error("The name is too long" + " " +e.getMessage());
throw new MeleteException("failed");
}
catch(IdUniquenessException e)
{
logger.error("Could not add this resource item to melete collection");
throw new MeleteException("failed");
}
catch(InconsistentException e)
{
logger.error("Invalid characters in collection title");
throw new MeleteException("failed");
}
catch(OverQuotaException e)
{
logger.error("Adding this resource would place this account over quota.To add this resource, some resources may need to be deleted.");
throw new MeleteException("failed");
}
catch(ServerOverloadException e)
{
logger.error("failed - internal error");
throw new MeleteException("failed");
}
catch(RuntimeException e)
{
logger.error("SectionPage.addResourcetoMeleteCollection ***** Unknown Exception ***** " + e.getMessage());
e.printStackTrace();
throw new MeleteException("failed");
}
} catch (Exception e) {
logger.error(e.toString());
}
finally{
meleteSecurityService.popAdvisor();
}
return resource.getId();
}
/*
*
*/
public List getAllResources(String uploadCollId)
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
return (getContentservice().getAllResources(uploadCollId));
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return null;
}
/*
*
*/
public ContentResource getResource(String resourceId) throws Exception
{
try
{
if (!isUserAuthor() && !isUserStudent())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
resourceId = URLDecoder.decode(resourceId,"UTF-8");
return (getContentservice().getResource(resourceId));
}
catch(Exception e)
{
logger.error(e.toString());
throw e;
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
}
public void checkResource(String resourceId) throws Exception
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
resourceId = URLDecoder.decode(resourceId,"UTF-8");
getContentservice().checkResource(resourceId);
return;
}
catch (IdUnusedException ex)
{
logger.debug("resource is not available so create one" + resourceId);
throw ex;
}
catch(Exception e)
{
logger.error(e.toString());
}
finally
{
// clear the security advisor
meleteSecurityService.popAdvisor();
}
return ;
}
/*
*
*/
public void editResource(String resourceId, String contentEditor) throws Exception
{
ContentResourceEdit edit = null;
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs collection");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
if (resourceId != null)
{
resourceId = URLDecoder.decode(resourceId,"UTF-8");
edit = getContentservice().editResource(resourceId);
edit.setContent(contentEditor.getBytes());
edit.setContentLength(contentEditor.length());
getContentservice().commitResource(edit);
edit = null;
}
return;
}
catch(Exception e)
{
logger.error("error saving editor content "+e.toString());
throw e;
}
finally
{
if(edit != null) getContentservice().cancelResource(edit);
// clear the security advisor
meleteSecurityService.popAdvisor();
}
}
/*
* before saving editor content, look for embedded images from local system
* and add them to collection
* if filename has # sign then throw error
* Do see diego's fix to paste from word works
*/
public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException
{
String checkforimgs = contentEditor;
// get collection id where the embedded files will go
String UploadCollId = getUploadCollectionId();
String fileName;
int startSrc =0;
int endSrc = 0;
String foundLink = null;
// look for local embedded images
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs");
return null;
}
// remove MSword comments
int wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx+19);
int endcommentIdx = checkforimgs.indexOf("<![endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+12);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
//for FCK editor inserted comments
wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx);
int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+14);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
contentEditor = checkforimgs;
// remove word comments code end
//check for form tag and remove it
checkforimgs = meleteUtil.findFormPattern(checkforimgs);
contentEditor = checkforimgs;
while(checkforimgs !=null)
{
// look for a href and img tag
ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs);
checkforimgs = (String)embedData.get(0);
if (embedData.size() > 1)
{
startSrc = ((Integer)embedData.get(1)).intValue();
endSrc = ((Integer)embedData.get(2)).intValue();
foundLink = (String) embedData.get(3);
}
if (endSrc <= 0) break;
// find filename
fileName = checkforimgs.substring(startSrc, endSrc);
String patternStr = fileName;
logger.debug("processing embed src" + fileName);
//process for local uploaded files
if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator)))
&& fileName.startsWith("file:/") )
{
// word paste fix
patternStr= meleteUtil.replace(patternStr,"\\","/");
contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr);
checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr);
fileName = patternStr;
fileName = fileName.substring(fileName.lastIndexOf("/")+1);
// if filename contains pound char then throw error
if(fileName.indexOf("#") != -1)
{
logger.error("embedded FILE contains hash or other characters " + fileName);
throw new MeleteException("embed_img_bad_filename");
}
// add the file to collection and move from uploads directory
// read data
try{
File re = new File(uploadHomeDir+File.separator+fileName);
byte[] data = new byte[(int)re.length()];
FileInputStream fis = new FileInputStream(re);
fis.read(data);
fis.close();
re.delete();
// add as a resource to uploads collection
String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1);
file_mime_type = ContentTypeImageService.getContentType(file_mime_type);
String newEmbedResourceId = null;
//If the resource already exists, use it
try
{
String checkResourceId = UploadCollId + "/" + fileName;
checkResource(checkResourceId);
newEmbedResourceId = checkResourceId;
}
catch (IdUnusedException ex2)
{
ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName);
newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res );
}
//add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
//set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
// in content editor replace the file found with resource reference url
String replaceStr = getResourceUrl(newEmbedResourceId);
replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),"");
logger.debug("repl;acestr in embedimage processing is " + replaceStr);
// Replace all occurrences of pattern in input
Pattern pattern = Pattern.compile(patternStr);
//Rashmi's change to fix infinite loop on uploading images
contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr);
}
catch(FileNotFoundException ff)
{
logger.error(ff.toString());
throw new MeleteException("embed_image_size_exceed");
}
}
// for internal links to make it relative
else
{
if (fileName.startsWith(ServerConfigurationService.getServerUrl()))
{
if (fileName.indexOf("/meleteDocs") != -1)
{
String findEntity = fileName.substring(fileName.indexOf("/access") + 7);
Reference ref = EntityManager.newReference(findEntity);
logger.debug("ref properties" + ref.getType() + "," + ref.getId());
String newEmbedResourceId = ref.getId();
newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", "");
if (sectiondb.getMeleteResource(newEmbedResourceId) == null)
{
// add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
// set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
}
}
String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), "");
contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr);
}
// process links and append http:// protocol if not provided
else if (!fileName.startsWith("/access")
&& foundLink != null
&& foundLink.equals("link")
&& !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:") || fileName
.startsWith("#")))
{
logger.debug("processing embed link src for appending protocol");
String replaceLinkStr = "http://" + fileName;
contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr);
checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr);
}
}
// add target if not provided
if(foundLink != null && foundLink.equals("link"))
{
String soFar = checkforimgs.substring(0,endSrc);
String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1);
String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2);
Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*=");
Matcher m = pa.matcher(checkTarget);
if(!m.find())
{
String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >");
checkforimgs = soFar + newTarget + laterPart;
contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget);
}
}
// iterate next
- checkforimgs =checkforimgs.substring(endSrc);
+ if(endSrc > 0 && endSrc <= checkforimgs.length())
+ checkforimgs =checkforimgs.substring(endSrc);
+ else checkforimgs = null;
startSrc=0; endSrc = 0; foundLink = null;
}
}
catch(MeleteException me) {throw me;}
catch(Exception e){logger.error(e.toString());e.printStackTrace();}
return contentEditor;
}
public List findAllEmbeddedImages(String sec_resId) throws Exception
{
try{
ContentResource cr = getResource(sec_resId);
String checkforImgs = new String(cr.getContent());
List secEmbedData = new ArrayList<String> (0);
int startSrc=0, endSrc=0;
if (checkforImgs == null || checkforImgs.length() == 0) return null;
while(checkforImgs != null)
{
// look for a href and img tag
ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforImgs);
checkforImgs = (String)embedData.get(0);
if (embedData.size() > 1)
{
startSrc = ((Integer)embedData.get(1)).intValue();
endSrc = ((Integer)embedData.get(2)).intValue();
}
if (endSrc <= 0) break;
// find filename and add just the ones which belongs to meleteDocs
String fileName = checkforImgs.substring(startSrc, endSrc);
if(fileName.startsWith("/access/meleteDocs/content"))
{
fileName = fileName.replace("/access/meleteDocs/content", "");
fileName = URLDecoder.decode(fileName,"UTF-8");
secEmbedData.add(fileName);
}
// iterate next
checkforImgs =checkforImgs.substring(endSrc);
startSrc=0; endSrc = 0;
}
return secEmbedData;
} catch(Exception e)
{
logger.debug("can't read section file" + sec_resId);
}
return null;
}
/*
* get the URL for replaceStr of embedded images
*/
public String getResourceUrl(String newResourceId)
{
try
{
meleteSecurityService.pushAdvisor();
newResourceId = URLDecoder.decode(newResourceId,"UTF-8");
return getContentservice().getUrl(newResourceId);
}
catch (Exception e)
{
e.printStackTrace();
return "";
}
finally
{
meleteSecurityService.popAdvisor();
}
}
public void copyIntoFolder(String fromColl,String toColl)
{
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform the copyIntoFolder function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
getContentservice().copyIntoFolder(fromColl, toColl);
}
catch(InconsistentException e)
{
logger.error("Inconsistent exception thrown");
}
catch(IdLengthException e)
{
logger.error("IdLength exception thrown");
}
catch(IdUniquenessException e)
{
logger.error("IdUniqueness exception thrown");
}
catch(PermissionException e)
{
logger.error("Permission to copy uploads collection is denied");
}
catch(IdUnusedException e)
{
logger.error("Failed to create uploads collection in second site");
}
catch(TypeException e)
{
logger.error("TypeException thrown: "+e.getMessage());
}
catch(InUseException e)
{
logger.error("InUseException thrown: "+e.getMessage());
}
catch(IdUsedException e)
{
logger.error("IdUsedException thrown");
}
catch(OverQuotaException e)
{
logger.error("Copying this collection would place this account over quota.");
}
catch(ServerOverloadException e)
{
logger.error("Server overload exception");
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
meleteSecurityService.popAdvisor();
}
}
public ContentCollection getCollection(String toColl)
{
ContentCollection toCollection = null;
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform the copyIntoFolder function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
toCollection = getContentservice().getCollection(toColl);
}
catch(IdUnusedException e1)
{
logger.error("IdUnusedException thrown: "+e1.getMessage());
}
catch(TypeException e1)
{
logger.error("TypeException thrown: "+e1.getMessage());
}
catch(PermissionException e1)
{
logger.error("Permission to get uploads collection is denied");
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
meleteSecurityService.popAdvisor();
}
return toCollection;
}
public void removeResource(String delRes_id) throws Exception
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform del resource function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
ContentResourceEdit edit = null;
try
{
edit = getContentservice().editResource(delRes_id);
getContentservice().removeResource(edit);
edit = null;
}
catch(IdUnusedException e1)
{
logger.error("IdUnusedException thrown: "+e1.getMessage() + delRes_id );
}
catch(TypeException e1)
{
logger.error("TypeException thrown: "+e1.getMessage());
}
catch(PermissionException e1)
{
logger.error("Permission to get uploads collection is denied");
}
catch (Exception e)
{
e.printStackTrace();
throw new MeleteException("delete_resource_fail");
}
finally
{
if(edit != null)getContentservice().cancelResource(edit);
meleteSecurityService.popAdvisor();
}
}
public void removeCollection(String delColl_id, String delSubColl_id) throws Exception
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform del resource function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
delColl_id= Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+delColl_id+ Entity.SEPARATOR;
if(delSubColl_id != null)
delColl_id = delColl_id.concat(delSubColl_id + Entity.SEPARATOR);
logger.debug("checking coll before delte" + delColl_id);
try
{
getContentservice().checkCollection(delColl_id);
getContentservice().removeCollection(delColl_id);
}
catch (IdUnusedException e1)
{
logger.error("IdUnusedException thrown: "+e1.getMessage());
}
catch(TypeException e1)
{
logger.error("TypeException thrown: "+e1.getMessage());
}
catch(PermissionException e1)
{
logger.error("Permission to get uploads collection is denied");
}
catch (Exception e)
{
logger.error("error deleting melete collection:" + e.getMessage());
throw new MeleteException("delete_resource_fail");
}
finally
{
meleteSecurityService.popAdvisor();
}
}
public void removeCourseCollection(String delColl_id) throws Exception
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform del resource function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
delColl_id= Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+delColl_id+ Entity.SEPARATOR;
logger.debug("checking course coll before delete: " + delColl_id);
getContentservice().checkCollection(delColl_id);
// if uploads directory remains and all modules are deleted
logger.debug("collection sz"+ getContentservice().getCollectionSize(delColl_id));
if(getContentservice().getCollectionSize(delColl_id) == 1)
{
List allEnt = getContentservice().getAllEntities(delColl_id);
for(Iterator i = allEnt.iterator(); i.hasNext();)
{
ContentEntity ce = (ContentEntity)i.next();
if(ce.isCollection() && (ce.getId().indexOf("module_") == -1))
getContentservice().removeCollection(delColl_id);
}
}
}
catch(IdUnusedException e1)
{
logger.error("IdUnusedException thrown from remove Course Collection: "+e1.getMessage());
}
catch(TypeException e1)
{
logger.error("TypeException thrown: "+e1.getMessage());
}
catch(PermissionException e1)
{
logger.error("Permission to get uploads collection is denied");
}
catch (Exception e)
{
throw new MeleteException("delete_resource_fail");
}
finally
{
meleteSecurityService.popAdvisor();
}
}
public String moveResource(String resourceId, String destinationColl) throws Exception
{
if (!isUserAuthor())
{
logger.info("User is not authorized to perform del resource function");
}
// setup a security advisor
meleteSecurityService.pushAdvisor();
try
{
getContentservice().checkResource(resourceId);
String newResId = getContentservice().moveIntoFolder(resourceId,destinationColl);
return newResId;
}
catch(IdUnusedException e1)
{
logger.error("IdUnusedException thrown from moveResource: "+e1.getMessage());
}
catch (Exception e)
{
throw new MeleteException("move_resource_fail");
}
finally
{
meleteSecurityService.popAdvisor();
}
return null;
}
/**
* @return Returns the logger.
*/
public void setLogger(Log logger) {
this.logger = logger;
}
/**
* @return Returns the contentservice.
*/
public ContentHostingService getContentservice() {
return contentservice;
}
/**
* @param contentservice The contentservice to set.
*/
public void setContentservice(ContentHostingService contentservice) {
this.contentservice = contentservice;
}
/**
* @return meleteSecurityService
*/
public MeleteSecurityService getMeleteSecurityService() {
return meleteSecurityService;
}
/**
* @param meleteSecurityService The meleteSecurityService to set.
*/
public void setMeleteSecurityService(MeleteSecurityService meleteSecurityService) {
this.meleteSecurityService = meleteSecurityService;
}
/**
* @return Returns the sectiondb.
*/
public SectionDB getSectiondb() {
return sectiondb;
}
/**
* @param sectiondb The sectiondb to set.
*/
public void setSectiondb(SectionDB sectiondb) {
this.sectiondb = sectiondb;
}
}
| true | true | public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException
{
String checkforimgs = contentEditor;
// get collection id where the embedded files will go
String UploadCollId = getUploadCollectionId();
String fileName;
int startSrc =0;
int endSrc = 0;
String foundLink = null;
// look for local embedded images
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs");
return null;
}
// remove MSword comments
int wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx+19);
int endcommentIdx = checkforimgs.indexOf("<![endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+12);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
//for FCK editor inserted comments
wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx);
int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+14);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
contentEditor = checkforimgs;
// remove word comments code end
//check for form tag and remove it
checkforimgs = meleteUtil.findFormPattern(checkforimgs);
contentEditor = checkforimgs;
while(checkforimgs !=null)
{
// look for a href and img tag
ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs);
checkforimgs = (String)embedData.get(0);
if (embedData.size() > 1)
{
startSrc = ((Integer)embedData.get(1)).intValue();
endSrc = ((Integer)embedData.get(2)).intValue();
foundLink = (String) embedData.get(3);
}
if (endSrc <= 0) break;
// find filename
fileName = checkforimgs.substring(startSrc, endSrc);
String patternStr = fileName;
logger.debug("processing embed src" + fileName);
//process for local uploaded files
if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator)))
&& fileName.startsWith("file:/") )
{
// word paste fix
patternStr= meleteUtil.replace(patternStr,"\\","/");
contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr);
checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr);
fileName = patternStr;
fileName = fileName.substring(fileName.lastIndexOf("/")+1);
// if filename contains pound char then throw error
if(fileName.indexOf("#") != -1)
{
logger.error("embedded FILE contains hash or other characters " + fileName);
throw new MeleteException("embed_img_bad_filename");
}
// add the file to collection and move from uploads directory
// read data
try{
File re = new File(uploadHomeDir+File.separator+fileName);
byte[] data = new byte[(int)re.length()];
FileInputStream fis = new FileInputStream(re);
fis.read(data);
fis.close();
re.delete();
// add as a resource to uploads collection
String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1);
file_mime_type = ContentTypeImageService.getContentType(file_mime_type);
String newEmbedResourceId = null;
//If the resource already exists, use it
try
{
String checkResourceId = UploadCollId + "/" + fileName;
checkResource(checkResourceId);
newEmbedResourceId = checkResourceId;
}
catch (IdUnusedException ex2)
{
ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName);
newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res );
}
//add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
//set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
// in content editor replace the file found with resource reference url
String replaceStr = getResourceUrl(newEmbedResourceId);
replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),"");
logger.debug("repl;acestr in embedimage processing is " + replaceStr);
// Replace all occurrences of pattern in input
Pattern pattern = Pattern.compile(patternStr);
//Rashmi's change to fix infinite loop on uploading images
contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr);
}
catch(FileNotFoundException ff)
{
logger.error(ff.toString());
throw new MeleteException("embed_image_size_exceed");
}
}
// for internal links to make it relative
else
{
if (fileName.startsWith(ServerConfigurationService.getServerUrl()))
{
if (fileName.indexOf("/meleteDocs") != -1)
{
String findEntity = fileName.substring(fileName.indexOf("/access") + 7);
Reference ref = EntityManager.newReference(findEntity);
logger.debug("ref properties" + ref.getType() + "," + ref.getId());
String newEmbedResourceId = ref.getId();
newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", "");
if (sectiondb.getMeleteResource(newEmbedResourceId) == null)
{
// add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
// set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
}
}
String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), "");
contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr);
}
// process links and append http:// protocol if not provided
else if (!fileName.startsWith("/access")
&& foundLink != null
&& foundLink.equals("link")
&& !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:") || fileName
.startsWith("#")))
{
logger.debug("processing embed link src for appending protocol");
String replaceLinkStr = "http://" + fileName;
contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr);
checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr);
}
}
// add target if not provided
if(foundLink != null && foundLink.equals("link"))
{
String soFar = checkforimgs.substring(0,endSrc);
String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1);
String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2);
Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*=");
Matcher m = pa.matcher(checkTarget);
if(!m.find())
{
String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >");
checkforimgs = soFar + newTarget + laterPart;
contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget);
}
}
// iterate next
checkforimgs =checkforimgs.substring(endSrc);
startSrc=0; endSrc = 0; foundLink = null;
}
}
catch(MeleteException me) {throw me;}
catch(Exception e){logger.error(e.toString());e.printStackTrace();}
return contentEditor;
}
| public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException
{
String checkforimgs = contentEditor;
// get collection id where the embedded files will go
String UploadCollId = getUploadCollectionId();
String fileName;
int startSrc =0;
int endSrc = 0;
String foundLink = null;
// look for local embedded images
try
{
if (!isUserAuthor())
{
logger.info("User is not authorized to access meleteDocs");
return null;
}
// remove MSword comments
int wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx+19);
int endcommentIdx = checkforimgs.indexOf("<![endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+12);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
//for FCK editor inserted comments
wordcommentIdx = -1;
while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1)
{
String pre = checkforimgs.substring(0,wordcommentIdx);
checkforimgs = checkforimgs.substring(wordcommentIdx);
int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->");
checkforimgs = checkforimgs.substring(endcommentIdx+14);
checkforimgs= pre + checkforimgs;
wordcommentIdx = -1;
}
contentEditor = checkforimgs;
// remove word comments code end
//check for form tag and remove it
checkforimgs = meleteUtil.findFormPattern(checkforimgs);
contentEditor = checkforimgs;
while(checkforimgs !=null)
{
// look for a href and img tag
ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs);
checkforimgs = (String)embedData.get(0);
if (embedData.size() > 1)
{
startSrc = ((Integer)embedData.get(1)).intValue();
endSrc = ((Integer)embedData.get(2)).intValue();
foundLink = (String) embedData.get(3);
}
if (endSrc <= 0) break;
// find filename
fileName = checkforimgs.substring(startSrc, endSrc);
String patternStr = fileName;
logger.debug("processing embed src" + fileName);
//process for local uploaded files
if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator)))
&& fileName.startsWith("file:/") )
{
// word paste fix
patternStr= meleteUtil.replace(patternStr,"\\","/");
contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr);
checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr);
fileName = patternStr;
fileName = fileName.substring(fileName.lastIndexOf("/")+1);
// if filename contains pound char then throw error
if(fileName.indexOf("#") != -1)
{
logger.error("embedded FILE contains hash or other characters " + fileName);
throw new MeleteException("embed_img_bad_filename");
}
// add the file to collection and move from uploads directory
// read data
try{
File re = new File(uploadHomeDir+File.separator+fileName);
byte[] data = new byte[(int)re.length()];
FileInputStream fis = new FileInputStream(re);
fis.read(data);
fis.close();
re.delete();
// add as a resource to uploads collection
String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1);
file_mime_type = ContentTypeImageService.getContentType(file_mime_type);
String newEmbedResourceId = null;
//If the resource already exists, use it
try
{
String checkResourceId = UploadCollId + "/" + fileName;
checkResource(checkResourceId);
newEmbedResourceId = checkResourceId;
}
catch (IdUnusedException ex2)
{
ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName);
newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res );
}
//add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
//set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
// in content editor replace the file found with resource reference url
String replaceStr = getResourceUrl(newEmbedResourceId);
replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),"");
logger.debug("repl;acestr in embedimage processing is " + replaceStr);
// Replace all occurrences of pattern in input
Pattern pattern = Pattern.compile(patternStr);
//Rashmi's change to fix infinite loop on uploading images
contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr);
}
catch(FileNotFoundException ff)
{
logger.error(ff.toString());
throw new MeleteException("embed_image_size_exceed");
}
}
// for internal links to make it relative
else
{
if (fileName.startsWith(ServerConfigurationService.getServerUrl()))
{
if (fileName.indexOf("/meleteDocs") != -1)
{
String findEntity = fileName.substring(fileName.indexOf("/access") + 7);
Reference ref = EntityManager.newReference(findEntity);
logger.debug("ref properties" + ref.getType() + "," + ref.getId());
String newEmbedResourceId = ref.getId();
newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", "");
if (sectiondb.getMeleteResource(newEmbedResourceId) == null)
{
// add in melete resource database table also
MeleteResource meleteResource = new MeleteResource();
meleteResource.setResourceId(newEmbedResourceId);
// set default license info to "I have not determined copyright yet" option
meleteResource.setLicenseCode(0);
sectiondb.insertResource(meleteResource);
}
}
String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), "");
contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr);
checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr);
}
// process links and append http:// protocol if not provided
else if (!fileName.startsWith("/access")
&& foundLink != null
&& foundLink.equals("link")
&& !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:") || fileName
.startsWith("#")))
{
logger.debug("processing embed link src for appending protocol");
String replaceLinkStr = "http://" + fileName;
contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr);
checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr);
}
}
// add target if not provided
if(foundLink != null && foundLink.equals("link"))
{
String soFar = checkforimgs.substring(0,endSrc);
String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1);
String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2);
Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*=");
Matcher m = pa.matcher(checkTarget);
if(!m.find())
{
String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >");
checkforimgs = soFar + newTarget + laterPart;
contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget);
}
}
// iterate next
if(endSrc > 0 && endSrc <= checkforimgs.length())
checkforimgs =checkforimgs.substring(endSrc);
else checkforimgs = null;
startSrc=0; endSrc = 0; foundLink = null;
}
}
catch(MeleteException me) {throw me;}
catch(Exception e){logger.error(e.toString());e.printStackTrace();}
return contentEditor;
}
|
diff --git a/src/com/android/ex/photo/PhotoViewActivity.java b/src/com/android/ex/photo/PhotoViewActivity.java
index aa8029e..1ba81a8 100644
--- a/src/com/android/ex/photo/PhotoViewActivity.java
+++ b/src/com/android/ex/photo/PhotoViewActivity.java
@@ -1,543 +1,541 @@
/*
* Copyright (C) 2011 Google Inc.
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ex.photo;
import android.app.ActionBar;
import android.app.ActionBar.OnMenuVisibilityListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import com.android.ex.photo.PhotoViewPager.InterceptType;
import com.android.ex.photo.PhotoViewPager.OnInterceptTouchListener;
import com.android.ex.photo.adapters.BaseFragmentPagerAdapter.OnFragmentPagerListener;
import com.android.ex.photo.adapters.PhotoPagerAdapter;
import com.android.ex.photo.fragments.PhotoViewFragment;
import com.android.ex.photo.loaders.PhotoPagerLoader;
import com.android.ex.photo.provider.PhotoContract;
import java.util.HashSet;
import java.util.Set;
/**
* Activity to view the contents of an album.
*/
public class PhotoViewActivity extends Activity implements
LoaderCallbacks<Cursor>, OnPageChangeListener, OnInterceptTouchListener,
OnFragmentPagerListener, OnMenuVisibilityListener {
/**
* Listener to be invoked for screen events.
*/
public static interface OnScreenListener {
/**
* The full screen state has changed.
*/
public void onFullScreenChanged(boolean fullScreen);
/**
* A new view has been activated and the previous view de-activated.
*/
public void onViewActivated();
/**
* Called when a right-to-left touch move intercept is about to occur.
*
* @param origX the raw x coordinate of the initial touch
* @param origY the raw y coordinate of the initial touch
* @return {@code true} if the touch should be intercepted.
*/
public boolean onInterceptMoveLeft(float origX, float origY);
/**
* Called when a left-to-right touch move intercept is about to occur.
*
* @param origX the raw x coordinate of the initial touch
* @param origY the raw y coordinate of the initial touch
* @return {@code true} if the touch should be intercepted.
*/
public boolean onInterceptMoveRight(float origX, float origY);
}
public static interface CursorChangedListener {
/**
* Called when the cursor that contains the photo list data
* is updated. Note that there is no guarantee that the cursor
* will be at the proper position.
* @param cursor the cursor containing the photo list data
*/
public void onCursorChanged(Cursor cursor);
}
private final static String STATE_ITEM_KEY =
"com.google.android.apps.plus.PhotoViewFragment.ITEM";
private final static String STATE_FULLSCREEN_KEY =
"com.google.android.apps.plus.PhotoViewFragment.FULLSCREEN";
private static final int LOADER_PHOTO_LIST = 1;
/** Count used when the real photo count is unknown [but, may be determined] */
public static final int ALBUM_COUNT_UNKNOWN = -1;
/** Argument key for the dialog message */
public static final String KEY_MESSAGE = "dialog_message";
public static int sMemoryClass;
/** The URI of the photos we're viewing; may be {@code null} */
private String mPhotosUri;
/** The index of the currently viewed photo */
private int mPhotoIndex;
/** The query projection to use; may be {@code null} */
private String[] mProjection;
/** The name of the particular photo being viewed. */
private String mPhotoName;
/** The total number of photos; only valid if {@link #mIsEmpty} is {@code false}. */
private int mAlbumCount = ALBUM_COUNT_UNKNOWN;
/** {@code true} if the view is empty. Otherwise, {@code false}. */
private boolean mIsEmpty;
/** The main pager; provides left/right swipe between photos */
private PhotoViewPager mViewPager;
/** Adapter to create pager views */
private PhotoPagerAdapter mAdapter;
/** Whether or not we're in "full screen" mode */
private boolean mFullScreen;
/** The set of listeners wanting full screen state */
private Set<OnScreenListener> mScreenListeners = new HashSet<OnScreenListener>();
/** The set of listeners wanting full screen state */
private Set<CursorChangedListener> mCursorListeners = new HashSet<CursorChangedListener>();
/** When {@code true}, restart the loader when the activity becomes active */
private boolean mRestartLoader;
/** Whether or not this activity is paused */
private boolean mIsPaused = true;
private Handler mActionBarHideHandler;
// TODO Find a better way to do this. We basically want the activity to display the
// "loading..." progress until the fragment takes over and shows it's own "loading..."
// progress [located in photo_header_view.xml]. We could potentially have all status displayed
// by the activity, but, that gets tricky when it comes to screen rotation. For now, we
// track the loading by this variable which is fragile and may cause phantom "loading..."
// text.
private long mActionBarHideDelayTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
- } else {
- mPhotoName = getResources().getString(R.string.photo_view_default_title);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
@Override
protected void onResume() {
super.onResume();
setFullScreen(mFullScreen, false);
mIsPaused = false;
if (mRestartLoader) {
mRestartLoader = false;
getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this);
}
}
@Override
protected void onPause() {
mIsPaused = true;
super.onPause();
}
@Override
public void onBackPressed() {
// If in full screen mode, toggle mode & eat the 'back'
if (mFullScreen) {
toggleFullScreen();
} else {
super.onBackPressed();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_ITEM_KEY, mViewPager.getCurrentItem());
outState.putBoolean(STATE_FULLSCREEN_KEY, mFullScreen);
}
public void addScreenListener(OnScreenListener listener) {
mScreenListeners.add(listener);
}
public void removeScreenListener(OnScreenListener listener) {
mScreenListeners.remove(listener);
}
public synchronized void addCursorListener(CursorChangedListener listener) {
mCursorListeners.add(listener);
}
public synchronized void removeCursorListener(CursorChangedListener listener) {
mCursorListeners.remove(listener);
}
public boolean isFragmentFullScreen(Fragment fragment) {
if (mViewPager == null || mAdapter == null || mAdapter.getCount() == 0) {
return mFullScreen;
}
return mFullScreen || (mViewPager.getCurrentItem() != mAdapter.getItemPosition(fragment));
}
public void toggleFullScreen() {
setFullScreen(!mFullScreen, true);
}
public void onPhotoRemoved(long photoId) {
final Cursor data = mAdapter.getCursor();
if (data == null) {
// Huh?! How would this happen?
return;
}
final int dataCount = data.getCount();
if (dataCount <= 1) {
finish();
return;
}
getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == LOADER_PHOTO_LIST) {
return new PhotoPagerLoader(this, Uri.parse(mPhotosUri), mProjection);
}
return null;
}
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
final int id = loader.getId();
if (id == LOADER_PHOTO_LIST) {
if (data == null || data.getCount() == 0) {
mIsEmpty = true;
} else {
mAlbumCount = data.getCount();
// Cannot do this directly; need to be out of the loader
new Handler().post(new Runnable() {
@Override
public void run() {
// We're paused; don't do anything now, we'll get re-invoked
// when the activity becomes active again
if (mIsPaused) {
mRestartLoader = true;
return;
}
mIsEmpty = false;
// set the selected photo
int itemIndex = mPhotoIndex;
// Use an index of 0 if the index wasn't specified or couldn't be found
if (itemIndex < 0) {
itemIndex = 0;
}
mAdapter.swapCursor(data);
notifyCursorListeners(data);
mViewPager.setCurrentItem(itemIndex, false);
setViewActivated();
}
});
}
}
}
private synchronized void notifyCursorListeners(Cursor data) {
// tell all of the objects listening for cursor changes
// that the cursor has changed
for (CursorChangedListener listener : mCursorListeners) {
listener.onCursorChanged(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPhotoIndex = position;
setViewActivated();
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageActivated(Fragment fragment) {
setViewActivated();
}
public boolean isFragmentActive(Fragment fragment) {
if (mViewPager == null || mAdapter == null) {
return false;
}
return mViewPager.getCurrentItem() == mAdapter.getItemPosition(fragment);
}
public void onFragmentVisible(PhotoViewFragment fragment) {
updateActionBar(fragment);
}
@Override
public InterceptType onTouchIntercept(float origX, float origY) {
boolean interceptLeft = false;
boolean interceptRight = false;
for (OnScreenListener listener : mScreenListeners) {
if (!interceptLeft) {
interceptLeft = listener.onInterceptMoveLeft(origX, origY);
}
if (!interceptRight) {
interceptRight = listener.onInterceptMoveRight(origX, origY);
}
listener.onViewActivated();
}
if (interceptLeft) {
if (interceptRight) {
return InterceptType.BOTH;
}
return InterceptType.LEFT;
} else if (interceptRight) {
return InterceptType.RIGHT;
}
return InterceptType.NONE;
}
/**
* Updates the title bar according to the value of {@link #mFullScreen}.
*/
private void setFullScreen(boolean fullScreen, boolean setDelayedRunnable) {
final boolean fullScreenChanged = (fullScreen != mFullScreen);
mFullScreen = fullScreen;
if (mFullScreen) {
setLightsOutMode(true);
cancelActionBarHideRunnable();
} else {
setLightsOutMode(false);
if (setDelayedRunnable) {
postActionBarHideRunnableWithDelay();
}
}
if (fullScreenChanged) {
for (OnScreenListener listener : mScreenListeners) {
listener.onFullScreenChanged(mFullScreen);
}
}
}
private void postActionBarHideRunnableWithDelay() {
mActionBarHideHandler.postDelayed(mActionBarHideRunnable,
mActionBarHideDelayTime);
}
private void cancelActionBarHideRunnable() {
mActionBarHideHandler.removeCallbacks(mActionBarHideRunnable);
}
private void setLightsOutMode(boolean enabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int flags = enabled
? View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
: View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
// using mViewPager since we have it and we need a view
mViewPager.setSystemUiVisibility(flags);
} else {
final ActionBar actionBar = getActionBar();
if (enabled) {
actionBar.hide();
} else {
actionBar.show();
}
int flags = enabled
? View.SYSTEM_UI_FLAG_LOW_PROFILE
: View.SYSTEM_UI_FLAG_VISIBLE;
mViewPager.setSystemUiVisibility(flags);
}
}
private Runnable mActionBarHideRunnable = new Runnable() {
@Override
public void run() {
PhotoViewActivity.this.setLightsOutMode(true);
}
};
public void setViewActivated() {
for (OnScreenListener listener : mScreenListeners) {
listener.onViewActivated();
}
}
/**
* Adjusts the activity title and subtitle to reflect the photo name and count.
*/
protected void updateActionBar(PhotoViewFragment fragment) {
final int position = mViewPager.getCurrentItem() + 1;
final String subtitle;
final boolean hasAlbumCount = mAlbumCount >= 0;
final Cursor cursor = getCursorAtProperPosition();
if (cursor != null) {
final int photoNameIndex = cursor.getColumnIndex(PhotoContract.PhotoViewColumns.NAME);
mPhotoName = cursor.getString(photoNameIndex);
}
if (mIsEmpty || !hasAlbumCount || position <= 0) {
subtitle = null;
} else {
subtitle = getResources().getString(R.string.photo_view_count, position, mAlbumCount);
}
final ActionBar actionBar = getActionBar();
actionBar.setTitle(mPhotoName);
actionBar.setSubtitle(subtitle);
}
/**
* Utility method that will return the cursor that contains the data
* at the current position so that it refers to the current image on screen.
* @return the cursor at the current position or
* null if no cursor exists or if the {@link PhotoViewPager} is null.
*/
public Cursor getCursorAtProperPosition() {
if (mViewPager == null) {
return null;
}
final int position = mViewPager.getCurrentItem();
final Cursor cursor = mAdapter.getCursor();
if (cursor == null) {
return null;
}
cursor.moveToPosition(position);
return cursor;
}
public Cursor getCursor() {
return (mAdapter == null) ? null : mAdapter.getCursor();
}
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
if (isVisible) {
cancelActionBarHideRunnable();
} else {
postActionBarHideRunnableWithDelay();
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
} else {
mPhotoName = getResources().getString(R.string.photo_view_default_title);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
|
diff --git a/src/com/android/mms/data/Contact.java b/src/com/android/mms/data/Contact.java
index 42f9037..d7290e4 100644
--- a/src/com/android/mms/data/Contact.java
+++ b/src/com/android/mms/data/Contact.java
@@ -1,489 +1,491 @@
package com.android.mms.data;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.ContentUris;
import android.content.Context;
import android.database.ContentObserver;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Presence;
import android.provider.Telephony.Mms;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.android.mms.ui.MessageUtils;
import com.android.mms.util.ContactInfoCache;
import com.android.mms.util.TaskStack;
import com.android.mms.LogTag;
public class Contact {
private static final String TAG = "Contact";
private static final boolean V = false;
private static final TaskStack sTaskStack = new TaskStack();
// private static final ContentObserver sContactsObserver = new ContentObserver(new Handler()) {
// @Override
// public void onChange(boolean selfUpdate) {
// if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
// log("contact changed, invalidate cache");
// }
// invalidateCache();
// }
// };
private static final ContentObserver sPresenceObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfUpdate) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("presence changed, invalidate cache");
}
invalidateCache();
}
};
private final HashSet<UpdateListener> mListeners = new HashSet<UpdateListener>();
private String mNumber;
private String mName;
private String mNameAndNumber; // for display, e.g. Fred Flintstone <670-782-1123>
private boolean mNumberIsModified; // true if the number is modified
private long mRecipientId; // used to find the Recipient cache entry
private String mLabel;
private long mPersonId;
private int mPresenceResId; // TODO: make this a state instead of a res ID
private String mPresenceText;
private BitmapDrawable mAvatar;
private boolean mIsStale;
@Override
public synchronized String toString() {
return String.format("{ number=%s, name=%s, nameAndNumber=%s, label=%s, person_id=%d }",
mNumber, mName, mNameAndNumber, mLabel, mPersonId);
}
public interface UpdateListener {
public void onUpdate(Contact updated);
}
private Contact(String number) {
mName = "";
setNumber(number);
mNumberIsModified = false;
mLabel = "";
mPersonId = 0;
mPresenceResId = 0;
mIsStale = true;
}
private static void logWithTrace(String msg, Object... format) {
Thread current = Thread.currentThread();
StackTraceElement[] stack = current.getStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(current.getId());
sb.append("] ");
sb.append(String.format(msg, format));
sb.append(" <- ");
int stop = stack.length > 7 ? 7 : stack.length;
for (int i = 3; i < stop; i++) {
String methodName = stack[i].getMethodName();
sb.append(methodName);
if ((i+1) != stop) {
sb.append(" <- ");
}
}
Log.d(TAG, sb.toString());
}
public static Contact get(String number, boolean canBlock) {
if (V) logWithTrace("get(%s, %s)", number, canBlock);
if (TextUtils.isEmpty(number)) {
throw new IllegalArgumentException("Contact.get called with null or empty number");
}
Contact contact = Cache.get(number);
if (contact == null) {
contact = new Contact(number);
Cache.put(contact);
}
if (contact.mIsStale) {
asyncUpdateContact(contact, canBlock);
}
return contact;
}
public static void invalidateCache() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("invalidateCache");
}
// force invalidate the contact info cache, so we will query for fresh info again.
// This is so we can get fresh presence info again on the screen, since the presence
// info changes pretty quickly, and we can't get change notifications when presence is
// updated in the ContactsProvider.
ContactInfoCache.getInstance().invalidateCache();
// While invalidating our local Cache doesn't remove the contacts, it will mark them
// stale so the next time we're asked for a particular contact, we'll return that
// stale contact and at the same time, fire off an asyncUpdateContact to update
// that contact's info in the background. UI elements using the contact typically
// call addListener() so they immediately get notified when the contact has been
// updated with the latest info. They redraw themselves when we call the
// listener's onUpdate().
Cache.invalidate();
}
private static String emptyIfNull(String s) {
return (s != null ? s : "");
}
private static boolean contactChanged(Contact orig, ContactInfoCache.CacheEntry newEntry) {
// The phone number should never change, so don't bother checking.
// TODO: Maybe update it if it has gotten longer, i.e. 650-234-5678 -> +16502345678?
String oldName = emptyIfNull(orig.mName);
String newName = emptyIfNull(newEntry.name);
if (!oldName.equals(newName)) {
if (V) Log.d(TAG, String.format("name changed: %s -> %s", oldName, newName));
return true;
}
String oldLabel = emptyIfNull(orig.mLabel);
String newLabel = emptyIfNull(newEntry.phoneLabel);
if (!oldLabel.equals(newLabel)) {
if (V) Log.d(TAG, String.format("label changed: %s -> %s", oldLabel, newLabel));
return true;
}
if (orig.mPersonId != newEntry.person_id) {
if (V) Log.d(TAG, "person id changed");
return true;
}
if (orig.mPresenceResId != newEntry.presenceResId) {
if (V) Log.d(TAG, "presence changed");
return true;
}
return false;
}
/**
* Handles the special case where the local ("Me") number is being looked up.
* Updates the contact with the "me" name and returns true if it is the
* local number, no-ops and returns false if it is not.
*/
private static boolean handleLocalNumber(Contact c) {
if (MessageUtils.isLocalNumber(c.mNumber)) {
c.mName = Cache.getContext().getString(com.android.internal.R.string.me);
c.updateNameAndNumber();
return true;
}
return false;
}
private static void asyncUpdateContact(final Contact c, boolean canBlock) {
if (c == null) {
return;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("asyncUpdateContact for " + c.toString() + " canBlock: " + canBlock +
" isStale: " + c.mIsStale);
}
Runnable r = new Runnable() {
public void run() {
updateContact(c);
}
};
if (canBlock) {
r.run();
} else {
sTaskStack.push(r);
}
}
private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
+ } else {
+ c.mIsStale = false;
}
}
}
public static String formatNameAndNumber(String name, String number) {
// Format like this: Mike Cleron <(650) 555-1234>
// Erick Tseng <(650) 555-1212>
// Tutankhamun <[email protected]>
// (408) 555-1289
String formattedNumber = number;
if (!Mms.isEmailAddress(number)) {
formattedNumber = PhoneNumberUtils.formatNumber(number);
}
if (!TextUtils.isEmpty(name) && !name.equals(number)) {
return name + " <" + formattedNumber + ">";
} else {
return formattedNumber;
}
}
public synchronized String getNumber() {
return mNumber;
}
public synchronized void setNumber(String number) {
mNumber = number;
updateNameAndNumber();
mNumberIsModified = true;
}
public boolean isNumberModified() {
return mNumberIsModified;
}
public void setIsNumberModified(boolean flag) {
mNumberIsModified = flag;
}
public synchronized String getName() {
if (TextUtils.isEmpty(mName)) {
return mNumber;
} else {
return mName;
}
}
public synchronized String getNameAndNumber() {
return mNameAndNumber;
}
private void updateNameAndNumber() {
mNameAndNumber = formatNameAndNumber(mName, mNumber);
}
public synchronized long getRecipientId() {
return mRecipientId;
}
public synchronized void setRecipientId(long id) {
mRecipientId = id;
}
public synchronized String getLabel() {
return mLabel;
}
public synchronized Uri getUri() {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, mPersonId);
}
public long getPersonId() {
return mPersonId;
}
public synchronized int getPresenceResId() {
return mPresenceResId;
}
public synchronized boolean existsInDatabase() {
return (mPersonId > 0);
}
public synchronized void addListener(UpdateListener l) {
boolean added = mListeners.add(l);
if (V && added) dumpListeners();
}
public synchronized void removeListener(UpdateListener l) {
boolean removed = mListeners.remove(l);
if (V && removed) dumpListeners();
}
public synchronized void dumpListeners() {
int i=0;
Log.i(TAG, "[Contact] dumpListeners(" + mNumber + ") size=" + mListeners.size());
for (UpdateListener listener : mListeners) {
Log.i(TAG, "["+ (i++) + "]" + listener);
}
}
public synchronized boolean isEmail() {
return Mms.isEmailAddress(mNumber);
}
public String getPresenceText() {
return mPresenceText;
}
public Drawable getAvatar(Drawable defaultValue) {
return mAvatar != null ? mAvatar : defaultValue;
}
public static void init(final Context context) {
Cache.init(context);
RecipientIdCache.init(context);
// it maybe too aggressive to listen for *any* contact changes, and rebuild MMS contact
// cache each time that occurs. Unless we can get targeted updates for the contacts we
// care about(which probably won't happen for a long time), we probably should just
// invalidate cache peoridically, or surgically.
/*
context.getContentResolver().registerContentObserver(
Contacts.CONTENT_URI, true, sContactsObserver);
*/
}
public static void dump() {
Cache.dump();
}
public static void startPresenceObserver() {
Cache.getContext().getContentResolver().registerContentObserver(
Presence.CONTENT_URI, true, sPresenceObserver);
}
public static void stopPresenceObserver() {
Cache.getContext().getContentResolver().unregisterContentObserver(sPresenceObserver);
}
private static class Cache {
private static Cache sInstance;
static Cache getInstance() { return sInstance; }
private final List<Contact> mCache;
private final Context mContext;
private Cache(Context context) {
mCache = new ArrayList<Contact>();
mContext = context;
}
static void init(Context context) {
sInstance = new Cache(context);
}
static Context getContext() {
return sInstance.mContext;
}
static void dump() {
synchronized (sInstance) {
Log.d(TAG, "**** Contact cache dump ****");
for (Contact c : sInstance.mCache) {
Log.d(TAG, c.toString());
}
}
}
private static Contact getEmail(String number) {
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
if (number.equalsIgnoreCase(c.mNumber)) {
return c;
}
}
return null;
}
}
static Contact get(String number) {
if (Mms.isEmailAddress(number))
return getEmail(number);
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
// if the numbers are an exact match (i.e. Google SMS), or if the phone
// number comparison returns a match, return the contact.
if (number.equals(c.mNumber) || PhoneNumberUtils.compare(number, c.mNumber)) {
return c;
}
}
return null;
}
}
static void put(Contact c) {
synchronized (sInstance) {
// We update cache entries in place so people with long-
// held references get updated.
if (get(c.mNumber) != null) {
throw new IllegalStateException("cache already contains " + c);
}
sInstance.mCache.add(c);
}
}
static String[] getNumbers() {
synchronized (sInstance) {
String[] numbers = new String[sInstance.mCache.size()];
int i = 0;
for (Contact c : sInstance.mCache) {
numbers[i++] = c.getNumber();
}
return numbers;
}
}
static List<Contact> getContacts() {
synchronized (sInstance) {
return new ArrayList<Contact>(sInstance.mCache);
}
}
static void invalidate() {
// Don't remove the contacts. Just mark them stale so we'll update their
// info, particularly their presence.
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
c.mIsStale = true;
}
}
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| true | true | private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
}
}
}
| private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
} else {
c.mIsStale = false;
}
}
}
|
diff --git a/src/interiores/business/controllers/DesignController.java b/src/interiores/business/controllers/DesignController.java
index 2b0af02..dfd7867 100644
--- a/src/interiores/business/controllers/DesignController.java
+++ b/src/interiores/business/controllers/DesignController.java
@@ -1,70 +1,70 @@
package interiores.business.controllers;
import interiores.business.models.FurnitureModel;
import interiores.business.models.Room;
import interiores.business.models.WantedFurniture;
import interiores.business.models.WishList;
import interiores.business.models.backtracking.FurnitureVariableSet;
import interiores.business.models.constraints.BinaryConstraintSet;
import interiores.business.models.constraints.UnaryConstraint;
import interiores.core.business.BusinessController;
import interiores.core.data.JAXBDataController;
import interiores.shared.backtracking.NoSolutionException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
*
* @author alvaro
*/
public class DesignController extends BusinessController
{
private boolean solutionFound = false;
private String lastSolution;
public DesignController(JAXBDataController data) {
super(data);
}
public void solve() {
WishList wishList = (WishList) data.get("wishList");
Room room = (Room) data.get("room");
Collection<WantedFurniture> furniture = wishList.getWantedFurniture();
List<List<FurnitureModel>> variableModels = new ArrayList();
List<List<UnaryConstraint>> variableConstraints = new ArrayList();
for (WantedFurniture wf : furniture) {
variableModels.add(wf.getType().getFurnitureModels());
- variableConstraints.add((List<UnaryConstraint>)wf.getConstraints());
+ variableConstraints.add(new ArrayList<UnaryConstraint>(wf.getConstraints()));
}
FurnitureVariableSet furVarSet = new FurnitureVariableSet(room, variableModels,
variableConstraints, new BinaryConstraintSet());
try {
furVarSet.solve();
solutionFound = true;
lastSolution = furVarSet.toString();
}
catch (NoSolutionException nse) {
solutionFound = false;
}
}
public boolean hasSolution() {
return solutionFound;
}
public String getDesign() {
return lastSolution;
}
}
| true | true | public void solve() {
WishList wishList = (WishList) data.get("wishList");
Room room = (Room) data.get("room");
Collection<WantedFurniture> furniture = wishList.getWantedFurniture();
List<List<FurnitureModel>> variableModels = new ArrayList();
List<List<UnaryConstraint>> variableConstraints = new ArrayList();
for (WantedFurniture wf : furniture) {
variableModels.add(wf.getType().getFurnitureModels());
variableConstraints.add((List<UnaryConstraint>)wf.getConstraints());
}
FurnitureVariableSet furVarSet = new FurnitureVariableSet(room, variableModels,
variableConstraints, new BinaryConstraintSet());
try {
furVarSet.solve();
solutionFound = true;
lastSolution = furVarSet.toString();
}
catch (NoSolutionException nse) {
solutionFound = false;
}
}
| public void solve() {
WishList wishList = (WishList) data.get("wishList");
Room room = (Room) data.get("room");
Collection<WantedFurniture> furniture = wishList.getWantedFurniture();
List<List<FurnitureModel>> variableModels = new ArrayList();
List<List<UnaryConstraint>> variableConstraints = new ArrayList();
for (WantedFurniture wf : furniture) {
variableModels.add(wf.getType().getFurnitureModels());
variableConstraints.add(new ArrayList<UnaryConstraint>(wf.getConstraints()));
}
FurnitureVariableSet furVarSet = new FurnitureVariableSet(room, variableModels,
variableConstraints, new BinaryConstraintSet());
try {
furVarSet.solve();
solutionFound = true;
lastSolution = furVarSet.toString();
}
catch (NoSolutionException nse) {
solutionFound = false;
}
}
|
diff --git a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
index c9ba2b92..a9c00333 100644
--- a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
+++ b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
@@ -1,261 +1,262 @@
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Copyright (C) 2008 CEJUG - Ceará Java Users Group
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This file is part of the CEJUG-CLASSIFIEDS Project - an open source classifieds system
originally used by CEJUG - Ceará Java Users Group.
The project is hosted https://cejug-classifieds.dev.java.net/
You can contact us through the mail [email protected]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
package net.java.dev.cejug.classifieds.service.endpoint.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.xml.ws.WebServiceException;
import net.java.dev.cejug.classifieds.adapter.SoapOrmAdapter;
import net.java.dev.cejug.classifieds.business.interfaces.AdvertisementAdapterLocal;
import net.java.dev.cejug.classifieds.business.interfaces.AdvertisementOperationsLocal;
import net.java.dev.cejug.classifieds.entity.AdvertisementEntity;
import net.java.dev.cejug.classifieds.entity.facade.AdvertisementFacadeLocal;
import net.java.dev.cejug.classifieds.entity.facade.EntityFacade;
import net.java.dev.cejug.classifieds.exception.RepositoryAccessException;
import net.java.dev.cejug_classifieds.metadata.attachments.AtavarImage;
import net.java.dev.cejug_classifieds.metadata.attachments.AvatarImageOrUrl;
import net.java.dev.cejug_classifieds.metadata.business.Advertisement;
import net.java.dev.cejug_classifieds.metadata.business.AdvertisementCollection;
import net.java.dev.cejug_classifieds.metadata.business.AdvertisementCollectionFilter;
import net.java.dev.cejug_classifieds.metadata.business.PublishingHeader;
import net.java.dev.cejug_classifieds.metadata.common.Customer;
/**
* TODO: to comment.
*
* @author $Author$
* @version $Rev$ ($Date$)
*/
@Stateless
public class AdvertisementOperations extends
AbstractCrudImpl<AdvertisementEntity, Advertisement> implements
AdvertisementOperationsLocal {
/**
* Persistence façade of Advertisement entities.
*/
@EJB
private transient AdvertisementFacadeLocal advFacade;
@EJB
private transient AdvertisementAdapterLocal advAdapter;
/**
* the global log manager, used to allow third party services to override
* the default logger.
*/
private static final Logger logger = Logger.getLogger(
AdvertisementOperations.class.getName(), "i18n/log");
@Override
protected SoapOrmAdapter<Advertisement, AdvertisementEntity> getAdapter() {
return advAdapter;
}
@Override
protected EntityFacade<AdvertisementEntity> getFacade() {
return advFacade;
}
public AdvertisementCollection loadAdvertisementOperation(
final AdvertisementCollectionFilter filter) {
// TODO: load advertisements from timetable.... filtering with periods,
// etc..
try {
AdvertisementCollection collection = new AdvertisementCollection();
List<AdvertisementEntity> entities = advFacade.readByCategory(Long
.parseLong(filter.getCategory()));
for (AdvertisementEntity entity : entities) {
collection.getAdvertisement().add(advAdapter.toSoap(entity));
}
return collection;
} catch (Exception e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
+ /*
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
- }
+ }*/
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (Exception e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
/**
* A customer can submit a resource URL or a resource content, more common
* in case of images (PNG/JPG). In this case, the server first store the
* image contents in the file system and refer its location in the database.
* This method receives an Avatar object, check it size and store it
* contents in the file system.
*
* @param l
* @param advertisement
* the advertisement containing attachments.
* @return the resource address.
* @throws RepositoryAccessException
* problems accessing the content repository.
*/
private String copyResourcesToRepository(String name, byte[] contents,
long customerId, long domainId) throws RepositoryAccessException {
if (contents == null || contents.length < 1) {
return null;
} else if (customerId < 1 || domainId < 1) {
throw new RepositoryAccessException("Unaccepted ID (customer id:"
+ customerId + ", domain: " + domainId);
} else {
String glassfishHome = System.getenv("AS_HOME");
String path = glassfishHome
+ "/domains/domain1/applications/j2ee-apps/cejug-classifieds-server/cejug-classifieds-server_war/resource/"
+ domainId + '/' + customerId;
String file = path + "/" + name;
File pathF = new File(path);
File fileF = new File(file);
try {
if (pathF.mkdirs() && fileF.createNewFile()) {
FileOutputStream out;
out = new FileOutputStream(file);
out.write(contents);
out.close();
String resourcePath = "http://fgaucho.dyndns.org:8080/cejug-classifieds-server/resource/"
+ domainId + "/" + customerId + "/" + name;
logger.info("resource created: " + resourcePath);
return resourcePath;
} else {
throw new RepositoryAccessException(
"error trying tocreate the resource path '" + file
+ "'");
}
} catch (IOException e) {
logger.severe(e.getMessage());
throw new RepositoryAccessException(e);
}
}
}
private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static String hashGravatarEmail(String email)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
byte[] bytes = md.digest(email.getBytes());
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int low = (int) (bytes[i] & 0x0f);
int high = (int) ((bytes[i] & 0xf0) >> 4);
sb.append(HEXADECIMAL[high]);
sb.append(HEXADECIMAL[low]);
}
return sb.toString();
}
}
| false | true | public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
}
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (Exception e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
| public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
/*
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
}*/
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (Exception e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
|
diff --git a/src/org/mozilla/javascript/TokenStream.java b/src/org/mozilla/javascript/TokenStream.java
index 852c4a4d..7ae7099b 100644
--- a/src/org/mozilla/javascript/TokenStream.java
+++ b/src/org/mozilla/javascript/TokenStream.java
@@ -1,1365 +1,1362 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape 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/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Roger Lawrence
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.*;
/**
* This class implements the JavaScript scanner.
*
* It is based on the C source files jsscan.c and jsscan.h
* in the jsref package.
*
* @see org.mozilla.javascript.Parser
*
* @author Mike McCabe
* @author Brendan Eich
*/
public class TokenStream {
/*
* JSTokenStream flags, mirroring those in jsscan.h. These are used
* by the parser to change/check the state of the scanner.
*/
public final static int
TSF_NEWLINES = 0x0001, // tokenize newlines
TSF_FUNCTION = 0x0002, // scanning inside function body
TSF_RETURN_EXPR = 0x0004, // function has 'return expr;'
TSF_RETURN_VOID = 0x0008, // function has 'return;'
TSF_REGEXP = 0x0010; // looking for a regular expression
/*
* For chars - because we need something out-of-range
* to check. (And checking EOF by exception is annoying.)
* Note distinction from EOF token type!
*/
private final static int
EOF_CHAR = -1;
/**
* Token types. These values correspond to JSTokenType values in
* jsscan.c.
*/
public final static int
// start enum
ERROR = -1, // well-known as the only code < EOF
EOF = 0, // end of file token - (not EOF_CHAR)
EOL = 1, // end of line
// Beginning here are interpreter bytecodes. Their values
// must not exceed 127.
POPV = 2,
ENTERWITH = 3,
LEAVEWITH = 4,
RETURN = 5,
GOTO = 6,
IFEQ = 7,
IFNE = 8,
DUP = 9,
SETNAME = 10,
BITOR = 11,
BITXOR = 12,
BITAND = 13,
EQ = 14,
NE = 15,
LT = 16,
LE = 17,
GT = 18,
GE = 19,
LSH = 20,
RSH = 21,
URSH = 22,
ADD = 23,
SUB = 24,
MUL = 25,
DIV = 26,
MOD = 27,
BITNOT = 28,
NEG = 29,
NEW = 30,
DELPROP = 31,
TYPEOF = 32,
NAMEINC = 33,
PROPINC = 34,
ELEMINC = 35,
NAMEDEC = 36,
PROPDEC = 37,
ELEMDEC = 38,
GETPROP = 39,
SETPROP = 40,
GETELEM = 41,
SETELEM = 42,
CALL = 43,
NAME = 44,
NUMBER = 45,
STRING = 46,
ZERO = 47,
ONE = 48,
NULL = 49,
THIS = 50,
FALSE = 51,
TRUE = 52,
SHEQ = 53, // shallow equality (===)
SHNE = 54, // shallow inequality (!==)
CLOSURE = 55,
REGEXP = 56,
POP = 57,
POS = 58,
VARINC = 59,
VARDEC = 60,
BINDNAME = 61,
THROW = 62,
IN = 63,
INSTANCEOF = 64,
GOSUB = 65,
RETSUB = 66,
CALLSPECIAL = 67,
GETTHIS = 68,
NEWTEMP = 69,
USETEMP = 70,
GETBASE = 71,
GETVAR = 72,
SETVAR = 73,
UNDEFINED = 74,
TRY = 75,
ENDTRY = 76,
NEWSCOPE = 77,
TYPEOFNAME = 78,
ENUMINIT = 79,
ENUMNEXT = 80,
GETPROTO = 81,
GETPARENT = 82,
SETPROTO = 83,
SETPARENT = 84,
SCOPE = 85,
GETSCOPEPARENT = 86,
THISFN = 87,
JTHROW = 88,
// End of interpreter bytecodes
SEMI = 89, // semicolon
LB = 90, // left and right brackets
RB = 91,
LC = 92, // left and right curlies (braces)
RC = 93,
LP = 94, // left and right parentheses
RP = 95,
COMMA = 96, // comma operator
ASSIGN = 97, // assignment ops (= += -= etc.)
HOOK = 98, // conditional (?:)
COLON = 99,
OR = 100, // logical or (||)
AND = 101, // logical and (&&)
EQOP = 102, // equality ops (== !=)
RELOP = 103, // relational ops (< <= > >=)
SHOP = 104, // shift ops (<< >> >>>)
UNARYOP = 105, // unary prefix operator
INC = 106, // increment/decrement (++ --)
DEC = 107,
DOT = 108, // member operator (.)
PRIMARY = 109, // true, false, null, this
FUNCTION = 110, // function keyword
EXPORT = 111, // export keyword
IMPORT = 112, // import keyword
IF = 113, // if keyword
ELSE = 114, // else keyword
SWITCH = 115, // switch keyword
CASE = 116, // case keyword
DEFAULT = 117, // default keyword
WHILE = 118, // while keyword
DO = 119, // do keyword
FOR = 120, // for keyword
BREAK = 121, // break keyword
CONTINUE = 122, // continue keyword
VAR = 123, // var keyword
WITH = 124, // with keyword
CATCH = 125, // catch keyword
FINALLY = 126, // finally keyword
RESERVED = 127, // reserved keywords
/** Added by Mike - these are JSOPs in the jsref, but I
* don't have them yet in the java implementation...
* so they go here. Also whatever I needed.
* Most of these go in the 'op' field when returning
* more general token types, eg. 'DIV' as the op of 'ASSIGN'.
*/
NOP = 128, // NOP
NOT = 129, // etc.
PRE = 130, // for INC, DEC nodes.
POST = 131,
/**
* For JSOPs associated with keywords...
* eg. op = THIS; token = PRIMARY
*/
VOID = 132,
/* types used for the parse tree - these never get returned
* by the scanner.
*/
BLOCK = 133, // statement block
ARRAYLIT = 134, // array literal
OBJLIT = 135, // object literal
LABEL = 136, // label
TARGET = 137,
LOOP = 138,
ENUMDONE = 139,
EXPRSTMT = 140,
PARENT = 141,
CONVERT = 142,
JSR = 143,
NEWLOCAL = 144,
USELOCAL = 145,
SCRIPT = 146, // top-level node for entire script
LAST_TOKEN = 146;
// end enum
public static String tokenToName(int token) {
if (Context.printTrees || Context.printICode) {
switch (token) {
case ERROR: return "error";
case EOF: return "eof";
case EOL: return "eol";
case POPV: return "popv";
case ENTERWITH: return "enterwith";
case LEAVEWITH: return "leavewith";
case RETURN: return "return";
case GOTO: return "goto";
case IFEQ: return "ifeq";
case IFNE: return "ifne";
case DUP: return "dup";
case SETNAME: return "setname";
case BITOR: return "bitor";
case BITXOR: return "bitxor";
case BITAND: return "bitand";
case EQ: return "eq";
case NE: return "ne";
case LT: return "lt";
case LE: return "le";
case GT: return "gt";
case GE: return "ge";
case LSH: return "lsh";
case RSH: return "rsh";
case URSH: return "ursh";
case ADD: return "add";
case SUB: return "sub";
case MUL: return "mul";
case DIV: return "div";
case MOD: return "mod";
case BITNOT: return "bitnot";
case NEG: return "neg";
case NEW: return "new";
case DELPROP: return "delprop";
case TYPEOF: return "typeof";
case NAMEINC: return "nameinc";
case PROPINC: return "propinc";
case ELEMINC: return "eleminc";
case NAMEDEC: return "namedec";
case PROPDEC: return "propdec";
case ELEMDEC: return "elemdec";
case GETPROP: return "getprop";
case SETPROP: return "setprop";
case GETELEM: return "getelem";
case SETELEM: return "setelem";
case CALL: return "call";
case NAME: return "name";
case NUMBER: return "number";
case STRING: return "string";
case ZERO: return "zero";
case ONE: return "one";
case NULL: return "null";
case THIS: return "this";
case FALSE: return "false";
case TRUE: return "true";
case SHEQ: return "sheq";
case SHNE: return "shne";
case CLOSURE: return "closure";
case REGEXP: return "object";
case POP: return "pop";
case POS: return "pos";
case VARINC: return "varinc";
case VARDEC: return "vardec";
case BINDNAME: return "bindname";
case THROW: return "throw";
case IN: return "in";
case INSTANCEOF: return "instanceof";
case GOSUB: return "gosub";
case RETSUB: return "retsub";
case CALLSPECIAL: return "callspecial";
case GETTHIS: return "getthis";
case NEWTEMP: return "newtemp";
case USETEMP: return "usetemp";
case GETBASE: return "getbase";
case GETVAR: return "getvar";
case SETVAR: return "setvar";
case UNDEFINED: return "undefined";
case TRY: return "try";
case ENDTRY: return "endtry";
case NEWSCOPE: return "newscope";
case TYPEOFNAME: return "typeofname";
case ENUMINIT: return "enuminit";
case ENUMNEXT: return "enumnext";
case GETPROTO: return "getproto";
case GETPARENT: return "getparent";
case SETPROTO: return "setproto";
case SETPARENT: return "setparent";
case SCOPE: return "scope";
case GETSCOPEPARENT: return "getscopeparent";
case THISFN: return "thisfn";
case JTHROW: return "jthrow";
case SEMI: return "semi";
case LB: return "lb";
case RB: return "rb";
case LC: return "lc";
case RC: return "rc";
case LP: return "lp";
case RP: return "rp";
case COMMA: return "comma";
case ASSIGN: return "assign";
case HOOK: return "hook";
case COLON: return "colon";
case OR: return "or";
case AND: return "and";
case EQOP: return "eqop";
case RELOP: return "relop";
case SHOP: return "shop";
case UNARYOP: return "unaryop";
case INC: return "inc";
case DEC: return "dec";
case DOT: return "dot";
case PRIMARY: return "primary";
case FUNCTION: return "function";
case EXPORT: return "export";
case IMPORT: return "import";
case IF: return "if";
case ELSE: return "else";
case SWITCH: return "switch";
case CASE: return "case";
case DEFAULT: return "default";
case WHILE: return "while";
case DO: return "do";
case FOR: return "for";
case BREAK: return "break";
case CONTINUE: return "continue";
case VAR: return "var";
case WITH: return "with";
case CATCH: return "catch";
case FINALLY: return "finally";
case RESERVED: return "reserved";
case NOP: return "nop";
case NOT: return "not";
case PRE: return "pre";
case POST: return "post";
case VOID: return "void";
case BLOCK: return "block";
case ARRAYLIT: return "arraylit";
case OBJLIT: return "objlit";
case LABEL: return "label";
case TARGET: return "target";
case LOOP: return "loop";
case ENUMDONE: return "enumdone";
case EXPRSTMT: return "exprstmt";
case PARENT: return "parent";
case CONVERT: return "convert";
case JSR: return "jsr";
case NEWLOCAL: return "newlocal";
case USELOCAL: return "uselocal";
case SCRIPT: return "script";
}
return "<unknown="+token+">";
}
return "";
}
/* This function uses the cached op, string and number fields in
* TokenStream; if getToken has been called since the passed token
* was scanned, the op or string printed may be incorrect.
*/
public String tokenToString(int token) {
if (Context.printTrees) {
String name = tokenToName(token);
switch (token) {
case UNARYOP:
case ASSIGN:
case PRIMARY:
case EQOP:
case SHOP:
case RELOP:
return name + " " + tokenToName(this.op);
case STRING:
case REGEXP:
case NAME:
return name + " `" + this.string + "'";
case NUMBER:
return "NUMBER " + this.number;
}
return name;
}
return "";
}
private int stringToKeyword(String name) {
// #string_id_map#
// The following assumes that EOF == 0
final int
Id_break = BREAK,
Id_case = CASE,
Id_continue = CONTINUE,
Id_default = DEFAULT,
Id_delete = DELPROP,
Id_do = DO,
Id_else = ELSE,
Id_export = EXPORT,
Id_false = PRIMARY | (FALSE << 8),
Id_for = FOR,
Id_function = FUNCTION,
Id_if = IF,
Id_in = RELOP | (IN << 8),
Id_new = NEW,
Id_null = PRIMARY | (NULL << 8),
Id_return = RETURN,
Id_switch = SWITCH,
Id_this = PRIMARY | (THIS << 8),
Id_true = PRIMARY | (TRUE << 8),
Id_typeof = UNARYOP | (TYPEOF << 8),
Id_var = VAR,
Id_void = UNARYOP | (VOID << 8),
Id_while = WHILE,
Id_with = WITH,
// the following are #ifdef RESERVE_JAVA_KEYWORDS in jsscan.c
Id_abstract = RESERVED,
Id_boolean = RESERVED,
Id_byte = RESERVED,
Id_catch = CATCH,
Id_char = RESERVED,
Id_class = RESERVED,
Id_const = RESERVED,
Id_debugger = RESERVED,
Id_double = RESERVED,
Id_enum = RESERVED,
Id_extends = RESERVED,
Id_final = RESERVED,
Id_finally = FINALLY,
Id_float = RESERVED,
Id_goto = RESERVED,
Id_implements = RESERVED,
Id_import = IMPORT,
Id_instanceof = RELOP | (INSTANCEOF << 8),
Id_int = RESERVED,
Id_interface = RESERVED,
Id_long = RESERVED,
Id_native = RESERVED,
Id_package = RESERVED,
Id_private = RESERVED,
Id_protected = RESERVED,
Id_public = RESERVED,
Id_short = RESERVED,
Id_static = RESERVED,
Id_super = RESERVED,
Id_synchronized = RESERVED,
Id_throw = THROW,
Id_throws = RESERVED,
Id_transient = RESERVED,
Id_try = TRY,
Id_volatile = RESERVED;
int id;
String s = name;
// #generated# Last update: 2001-06-01 17:45:01 CEST
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 2: c=s.charAt(1);
if (c=='f') { if (s.charAt(0)=='i') {id=Id_if; break L0;} }
else if (c=='n') { if (s.charAt(0)=='i') {id=Id_in; break L0;} }
else if (c=='o') { if (s.charAt(0)=='d') {id=Id_do; break L0;} }
break L;
case 3: switch (s.charAt(0)) {
case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} break L;
case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') {id=Id_int; break L0;} break L;
case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') {id=Id_new; break L0;} break L;
case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') {id=Id_try; break L0;} break L;
case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_var; break L0;} break L;
} break L;
case 4: switch (s.charAt(0)) {
case 'b': X="byte";id=Id_byte; break L;
case 'c': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') {id=Id_case; break L0;} }
else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') {id=Id_char; break L0;} }
break L;
case 'e': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') {id=Id_else; break L0;} }
else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') {id=Id_enum; break L0;} }
break L;
case 'g': X="goto";id=Id_goto; break L;
case 'l': X="long";id=Id_long; break L;
case 'n': X="null";id=Id_null; break L;
case 't': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') {id=Id_true; break L0;} }
else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') {id=Id_this; break L0;} }
break L;
case 'v': X="void";id=Id_void; break L;
case 'w': X="with";id=Id_with; break L;
} break L;
case 5: switch (s.charAt(2)) {
case 'a': X="class";id=Id_class; break L;
case 'e': X="break";id=Id_break; break L;
case 'i': X="while";id=Id_while; break L;
case 'l': X="false";id=Id_false; break L;
case 'n': c=s.charAt(0);
if (c=='c') { X="const";id=Id_const; }
else if (c=='f') { X="final";id=Id_final; }
break L;
case 'o': c=s.charAt(0);
if (c=='f') { X="float";id=Id_float; }
else if (c=='s') { X="short";id=Id_short; }
break L;
case 'p': X="super";id=Id_super; break L;
case 'r': X="throw";id=Id_throw; break L;
case 't': X="catch";id=Id_catch; break L;
} break L;
case 6: switch (s.charAt(1)) {
case 'a': X="native";id=Id_native; break L;
case 'e': c=s.charAt(0);
if (c=='d') { X="delete";id=Id_delete; }
else if (c=='r') { X="return";id=Id_return; }
break L;
case 'h': X="throws";id=Id_throws; break L;
case 'm': X="import";id=Id_import; break L;
case 'o': X="double";id=Id_double; break L;
case 't': X="static";id=Id_static; break L;
case 'u': X="public";id=Id_public; break L;
case 'w': X="switch";id=Id_switch; break L;
case 'x': X="export";id=Id_export; break L;
case 'y': X="typeof";id=Id_typeof; break L;
} break L;
case 7: switch (s.charAt(1)) {
case 'a': X="package";id=Id_package; break L;
case 'e': X="default";id=Id_default; break L;
case 'i': X="finally";id=Id_finally; break L;
case 'o': X="boolean";id=Id_boolean; break L;
case 'r': X="private";id=Id_private; break L;
case 'x': X="extends";id=Id_extends; break L;
} break L;
case 8: switch (s.charAt(0)) {
case 'a': X="abstract";id=Id_abstract; break L;
case 'c': X="continue";id=Id_continue; break L;
case 'd': X="debugger";id=Id_debugger; break L;
case 'f': X="function";id=Id_function; break L;
case 'v': X="volatile";id=Id_volatile; break L;
} break L;
case 9: c=s.charAt(0);
if (c=='i') { X="interface";id=Id_interface; }
else if (c=='p') { X="protected";id=Id_protected; }
else if (c=='t') { X="transient";id=Id_transient; }
break L;
case 10: c=s.charAt(1);
if (c=='m') { X="implements";id=Id_implements; }
else if (c=='n') { X="instanceof";id=Id_instanceof; }
break L;
case 12: X="synchronized";id=Id_synchronized; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
// #/string_id_map#
if (id == 0) { return EOF; }
this.op = id >> 8;
return id & 0xff;
}
public TokenStream(Reader in, Scriptable scope,
String sourceName, int lineno)
{
this.in = new LineBuffer(in, lineno);
this.scope = scope;
this.pushbackToken = EOF;
this.sourceName = sourceName;
flags = 0;
}
public Scriptable getScope() {
return scope;
}
/* return and pop the token from the stream if it matches...
* otherwise return null
*/
public boolean matchToken(int toMatch) throws IOException {
int token = getToken();
if (token == toMatch)
return true;
// didn't match, push back token
tokenno--;
this.pushbackToken = token;
return false;
}
public void clearPushback() {
this.pushbackToken = EOF;
}
public void ungetToken(int tt) {
if (this.pushbackToken != EOF && tt != ERROR) {
String message = Context.getMessage2("msg.token.replaces.pushback",
tokenToString(tt), tokenToString(this.pushbackToken));
throw new RuntimeException(message);
}
this.pushbackToken = tt;
tokenno--;
}
public int peekToken() throws IOException {
int result = getToken();
this.pushbackToken = result;
tokenno--;
return result;
}
public int peekTokenSameLine() throws IOException {
int result;
flags |= TSF_NEWLINES; // SCAN_NEWLINES from jsscan.h
result = peekToken();
flags &= ~TSF_NEWLINES; // HIDE_NEWLINES from jsscan.h
if (this.pushbackToken == EOL)
this.pushbackToken = EOF;
return result;
}
protected static boolean isJSIdentifier(String s) {
int length = s.length();
if (length == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i=1; i<length; i++) {
char c = s.charAt(i);
if (!Character.isJavaIdentifierPart(c))
if (c == '\\')
if (! ((i + 5) < length)
&& (s.charAt(i + 1) == 'u')
&& 0 <= xDigitToInt(s.charAt(i + 2))
&& 0 <= xDigitToInt(s.charAt(i + 3))
&& 0 <= xDigitToInt(s.charAt(i + 4))
&& 0 <= xDigitToInt(s.charAt(i + 5)))
return false;
}
return true;
}
private static boolean isAlpha(int c) {
return ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z'));
}
static boolean isDigit(int c) {
return (c >= '0' && c <= '9');
}
static int xDigitToInt(int c) {
if ('0' <= c && c <= '9') { return c - '0'; }
if ('a' <= c && c <= 'f') { return c - ('a' - 10); }
if ('A' <= c && c <= 'F') { return c - ('A' - 10); }
return -1;
}
/* As defined in ECMA. jsscan.c uses C isspace() (which allows
* \v, I think.) note that code in in.read() implicitly accepts
* '\r' == \u000D as well.
*/
public static boolean isJSSpace(int c) {
return (c == '\u0020' || c == '\u0009'
|| c == '\u000C' || c == '\u000B'
|| c == '\u00A0'
|| Character.getType((char)c) == Character.SPACE_SEPARATOR);
}
public static boolean isJSLineTerminator(int c) {
return (c == '\n' || c == '\r'
|| c == 0x2028 || c == 0x2029);
}
public int getToken() throws IOException {
int c;
tokenno++;
// Check for pushed-back token
if (this.pushbackToken != EOF) {
int result = this.pushbackToken;
this.pushbackToken = EOF;
return result;
}
// Eat whitespace, possibly sensitive to newlines.
do {
c = in.read();
if (c == '\n')
if ((flags & TSF_NEWLINES) != 0)
break;
} while (isJSSpace(c) || c == '\n');
if (c == EOF_CHAR)
return EOF;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = in.read();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
c = '\\';
in.unread();
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
reportSyntaxError("msg.invalid.escape", null);
return ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = in.read();
if (c == '\\') {
c = in.read();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
} else {
if (!Character.isJavaIdentifierPart((char)c)) {
break;
}
addToString(c);
}
}
}
in.unread();
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != EOF) {
if (result != RESERVED) {
return result;
}
else if (!Context.getContext().hasFeature(
Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER))
{
return result;
}
else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript standard,
// treat it as name but issue warning
Object[] errArgs = { str };
reportSyntaxWarning("msg.reserved.keyword", errArgs);
}
}
}
this.string = str;
return NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(in.peek()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = in.read();
if (c == 'x' || c == 'X') {
base = 16;
c = in.read();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= xDigitToInt(c)) {
addToString(c);
c = in.read();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
Object[] errArgs = { c == '8' ? "8" : "9" };
reportSyntaxWarning("msg.bad.octal.literal", errArgs);
base = 10;
}
addToString(c);
c = in.read();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = in.read();
if (c == '+' || c == '-') {
addToString(c);
c = in.read();
}
if (!isDigit(c)) {
reportSyntaxError("msg.missing.exponent", null);
return ERROR;
}
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
}
in.unread();
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = (Double.valueOf(numString)).doubleValue();
}
catch (NumberFormatException ex) {
Object[] errArgs = { ex.getMessage() };
reportSyntaxError("msg.caught.nfe", errArgs);
return ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
int val = 0;
stringBufferTop = 0;
c = in.read();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.string.lit", null);
return ERROR;
}
if (c == '\\') {
// We've hit an escaped character
c = in.read();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u': {
/*
* Get 4 hex digits; if the u escape is not
* followed by 4 hex digits, use 'u' + the literal
* character sequence that follows.
*/
int escapeStart = stringBufferTop;
addToString('u');
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
} break;
case 'x': {
/* Get 2 hex digits, defaulting to 'x' + literal
* sequence, as above.
*/
c = in.read();
int escapeVal = xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
} break;
- default: if (isDigit(c) && c < '8') {
+ default: if ('0' <= c && c < '8') {
val = c - '0';
c = in.read();
- if (isDigit(c) && c < '8') {
+ if ('0' <= c && c < '8') {
val = 8 * val + c - '0';
c = in.read();
- if (isDigit(c) && c < '8') {
+ if ('0' <= c && c < '8' && val <= 037) {
+ // c is 3rd char of octal sequence only if
+ // the resulting val <= 0377
val = 8 * val + c - '0';
c = in.read();
}
}
in.unread();
- if (val > 0377) {
- reportSyntaxError("msg.oct.esc.too.large",
- null);
- return ERROR;
- }
c = val;
}
}
}
addToString(c);
c = in.read();
}
this.string = getStringFromBuffer();
return STRING;
}
switch (c)
{
case '\n': return EOL;
case ';': return SEMI;
case '[': return LB;
case ']': return RB;
case '{': return LC;
case '}': return RC;
case '(': return LP;
case ')': return RP;
case ',': return COMMA;
case '?': return HOOK;
case ':': return COLON;
case '.': return DOT;
case '|':
if (in.match('|')) {
return OR;
} else if (in.match('=')) {
this.op = BITOR;
return ASSIGN;
} else {
return BITOR;
}
case '^':
if (in.match('=')) {
this.op = BITXOR;
return ASSIGN;
} else {
return BITXOR;
}
case '&':
if (in.match('&')) {
return AND;
} else if (in.match('=')) {
this.op = BITAND;
return ASSIGN;
} else {
return BITAND;
}
case '=':
if (in.match('=')) {
if (in.match('='))
this.op = SHEQ;
else
this.op = EQ;
return EQOP;
} else {
this.op = NOP;
return ASSIGN;
}
case '!':
if (in.match('=')) {
if (in.match('='))
this.op = SHNE;
else
this.op = NE;
return EQOP;
} else {
this.op = NOT;
return UNARYOP;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (in.match('!')) {
if (in.match('-')) {
if (in.match('-')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken(); // in place of 'goto retry'
}
in.unread();
}
in.unread();
}
if (in.match('<')) {
if (in.match('=')) {
this.op = LSH;
return ASSIGN;
} else {
this.op = LSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = LE;
return RELOP;
} else {
this.op = LT;
return RELOP;
}
}
case '>':
if (in.match('>')) {
if (in.match('>')) {
if (in.match('=')) {
this.op = URSH;
return ASSIGN;
} else {
this.op = URSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = RSH;
return ASSIGN;
} else {
this.op = RSH;
return SHOP;
}
}
} else {
if (in.match('=')) {
this.op = GE;
return RELOP;
} else {
this.op = GT;
return RELOP;
}
}
case '*':
if (in.match('=')) {
this.op = MUL;
return ASSIGN;
} else {
return MUL;
}
case '/':
// is it a // comment?
if (in.match('/')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken();
}
if (in.match('*')) {
while ((c = in.read()) != -1 &&
!(c == '*' && in.match('/'))) {
; // empty loop body
}
if (c == EOF_CHAR) {
reportSyntaxError("msg.unterminated.comment", null);
return ERROR;
}
return getToken(); // `goto retry'
}
// is it a regexp?
if ((flags & TSF_REGEXP) != 0) {
stringBufferTop = 0;
while ((c = in.read()) != '/') {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.re.lit", null);
return ERROR;
}
if (c == '\\') {
addToString(c);
c = in.read();
}
addToString(c);
}
int reEnd = stringBufferTop;
while (true) {
if (in.match('g'))
addToString('g');
else if (in.match('i'))
addToString('i');
else if (in.match('m'))
addToString('m');
else
break;
}
if (isAlpha(in.peek())) {
reportSyntaxError("msg.invalid.re.flag", null);
return ERROR;
}
this.string = new String(stringBuffer, 0, reEnd);
this.regExpFlags = new String(stringBuffer, reEnd,
stringBufferTop - reEnd);
return REGEXP;
}
if (in.match('=')) {
this.op = DIV;
return ASSIGN;
} else {
return DIV;
}
case '%':
this.op = MOD;
if (in.match('=')) {
return ASSIGN;
} else {
return MOD;
}
case '~':
this.op = BITNOT;
return UNARYOP;
case '+':
case '-':
if (in.match('=')) {
if (c == '+') {
this.op = ADD;
return ASSIGN;
} else {
this.op = SUB;
return ASSIGN;
}
} else if (in.match((char) c)) {
if (c == '+') {
return INC;
} else {
return DEC;
}
} else if (c == '-') {
return SUB;
} else {
return ADD;
}
default:
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
}
private String getStringFromBuffer() {
return new String(stringBuffer, 0, stringBufferTop);
}
private void addToString(int c) {
if (stringBufferTop == stringBuffer.length) {
char[] tmp = new char[stringBuffer.length * 2];
System.arraycopy(stringBuffer, 0, tmp, 0, stringBufferTop);
stringBuffer = tmp;
}
stringBuffer[stringBufferTop++] = (char)c;
}
public void reportSyntaxError(String messageProperty, Object[] args) {
String message = Context.getMessage(messageProperty, args);
if (scope != null) {
// We're probably in an eval. Need to throw an exception.
throw NativeGlobal.constructError(
Context.getContext(), "SyntaxError",
message, scope, getSourceName(),
getLineno(), getOffset(), getLine());
} else {
Context.reportError(message, getSourceName(),
getLineno(), getLine(), getOffset());
}
}
private void reportSyntaxWarning(String messageProperty, Object[] args) {
String message = Context.getMessage(messageProperty, args);
Context.reportWarning(message, getSourceName(),
getLineno(), getLine(), getOffset());
}
public String getSourceName() { return sourceName; }
public int getLineno() { return in.getLineno(); }
public int getOp() { return op; }
public String getString() { return string; }
public double getNumber() { return number; }
public String getLine() { return in.getLine(); }
public int getOffset() { return in.getOffset(); }
public int getTokenno() { return tokenno; }
public boolean eof() { return in.eof(); }
// instance variables
private LineBuffer in;
/* for TSF_REGEXP, etc.
* should this be manipulated by gettor/settor functions?
* should it be passed to getToken();
*/
public int flags;
public String regExpFlags;
private String sourceName;
private String line;
private Scriptable scope;
private int pushbackToken;
private int tokenno;
private int op;
// Set this to an inital non-null value so that the Parser has
// something to retrieve even if an error has occured and no
// string is found. Fosters one class of error, but saves lots of
// code.
private String string = "";
private double number;
private char[] stringBuffer = new char[128];
private int stringBufferTop;
private static final boolean checkSelf = Context.check && true;
}
| false | true | public int getToken() throws IOException {
int c;
tokenno++;
// Check for pushed-back token
if (this.pushbackToken != EOF) {
int result = this.pushbackToken;
this.pushbackToken = EOF;
return result;
}
// Eat whitespace, possibly sensitive to newlines.
do {
c = in.read();
if (c == '\n')
if ((flags & TSF_NEWLINES) != 0)
break;
} while (isJSSpace(c) || c == '\n');
if (c == EOF_CHAR)
return EOF;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = in.read();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
c = '\\';
in.unread();
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
reportSyntaxError("msg.invalid.escape", null);
return ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = in.read();
if (c == '\\') {
c = in.read();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
} else {
if (!Character.isJavaIdentifierPart((char)c)) {
break;
}
addToString(c);
}
}
}
in.unread();
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != EOF) {
if (result != RESERVED) {
return result;
}
else if (!Context.getContext().hasFeature(
Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER))
{
return result;
}
else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript standard,
// treat it as name but issue warning
Object[] errArgs = { str };
reportSyntaxWarning("msg.reserved.keyword", errArgs);
}
}
}
this.string = str;
return NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(in.peek()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = in.read();
if (c == 'x' || c == 'X') {
base = 16;
c = in.read();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= xDigitToInt(c)) {
addToString(c);
c = in.read();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
Object[] errArgs = { c == '8' ? "8" : "9" };
reportSyntaxWarning("msg.bad.octal.literal", errArgs);
base = 10;
}
addToString(c);
c = in.read();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = in.read();
if (c == '+' || c == '-') {
addToString(c);
c = in.read();
}
if (!isDigit(c)) {
reportSyntaxError("msg.missing.exponent", null);
return ERROR;
}
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
}
in.unread();
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = (Double.valueOf(numString)).doubleValue();
}
catch (NumberFormatException ex) {
Object[] errArgs = { ex.getMessage() };
reportSyntaxError("msg.caught.nfe", errArgs);
return ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
int val = 0;
stringBufferTop = 0;
c = in.read();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.string.lit", null);
return ERROR;
}
if (c == '\\') {
// We've hit an escaped character
c = in.read();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u': {
/*
* Get 4 hex digits; if the u escape is not
* followed by 4 hex digits, use 'u' + the literal
* character sequence that follows.
*/
int escapeStart = stringBufferTop;
addToString('u');
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
} break;
case 'x': {
/* Get 2 hex digits, defaulting to 'x' + literal
* sequence, as above.
*/
c = in.read();
int escapeVal = xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
} break;
default: if (isDigit(c) && c < '8') {
val = c - '0';
c = in.read();
if (isDigit(c) && c < '8') {
val = 8 * val + c - '0';
c = in.read();
if (isDigit(c) && c < '8') {
val = 8 * val + c - '0';
c = in.read();
}
}
in.unread();
if (val > 0377) {
reportSyntaxError("msg.oct.esc.too.large",
null);
return ERROR;
}
c = val;
}
}
}
addToString(c);
c = in.read();
}
this.string = getStringFromBuffer();
return STRING;
}
switch (c)
{
case '\n': return EOL;
case ';': return SEMI;
case '[': return LB;
case ']': return RB;
case '{': return LC;
case '}': return RC;
case '(': return LP;
case ')': return RP;
case ',': return COMMA;
case '?': return HOOK;
case ':': return COLON;
case '.': return DOT;
case '|':
if (in.match('|')) {
return OR;
} else if (in.match('=')) {
this.op = BITOR;
return ASSIGN;
} else {
return BITOR;
}
case '^':
if (in.match('=')) {
this.op = BITXOR;
return ASSIGN;
} else {
return BITXOR;
}
case '&':
if (in.match('&')) {
return AND;
} else if (in.match('=')) {
this.op = BITAND;
return ASSIGN;
} else {
return BITAND;
}
case '=':
if (in.match('=')) {
if (in.match('='))
this.op = SHEQ;
else
this.op = EQ;
return EQOP;
} else {
this.op = NOP;
return ASSIGN;
}
case '!':
if (in.match('=')) {
if (in.match('='))
this.op = SHNE;
else
this.op = NE;
return EQOP;
} else {
this.op = NOT;
return UNARYOP;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (in.match('!')) {
if (in.match('-')) {
if (in.match('-')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken(); // in place of 'goto retry'
}
in.unread();
}
in.unread();
}
if (in.match('<')) {
if (in.match('=')) {
this.op = LSH;
return ASSIGN;
} else {
this.op = LSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = LE;
return RELOP;
} else {
this.op = LT;
return RELOP;
}
}
case '>':
if (in.match('>')) {
if (in.match('>')) {
if (in.match('=')) {
this.op = URSH;
return ASSIGN;
} else {
this.op = URSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = RSH;
return ASSIGN;
} else {
this.op = RSH;
return SHOP;
}
}
} else {
if (in.match('=')) {
this.op = GE;
return RELOP;
} else {
this.op = GT;
return RELOP;
}
}
case '*':
if (in.match('=')) {
this.op = MUL;
return ASSIGN;
} else {
return MUL;
}
case '/':
// is it a // comment?
if (in.match('/')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken();
}
if (in.match('*')) {
while ((c = in.read()) != -1 &&
!(c == '*' && in.match('/'))) {
; // empty loop body
}
if (c == EOF_CHAR) {
reportSyntaxError("msg.unterminated.comment", null);
return ERROR;
}
return getToken(); // `goto retry'
}
// is it a regexp?
if ((flags & TSF_REGEXP) != 0) {
stringBufferTop = 0;
while ((c = in.read()) != '/') {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.re.lit", null);
return ERROR;
}
if (c == '\\') {
addToString(c);
c = in.read();
}
addToString(c);
}
int reEnd = stringBufferTop;
while (true) {
if (in.match('g'))
addToString('g');
else if (in.match('i'))
addToString('i');
else if (in.match('m'))
addToString('m');
else
break;
}
if (isAlpha(in.peek())) {
reportSyntaxError("msg.invalid.re.flag", null);
return ERROR;
}
this.string = new String(stringBuffer, 0, reEnd);
this.regExpFlags = new String(stringBuffer, reEnd,
stringBufferTop - reEnd);
return REGEXP;
}
if (in.match('=')) {
this.op = DIV;
return ASSIGN;
} else {
return DIV;
}
case '%':
this.op = MOD;
if (in.match('=')) {
return ASSIGN;
} else {
return MOD;
}
case '~':
this.op = BITNOT;
return UNARYOP;
case '+':
case '-':
if (in.match('=')) {
if (c == '+') {
this.op = ADD;
return ASSIGN;
} else {
this.op = SUB;
return ASSIGN;
}
} else if (in.match((char) c)) {
if (c == '+') {
return INC;
} else {
return DEC;
}
} else if (c == '-') {
return SUB;
} else {
return ADD;
}
default:
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
}
| public int getToken() throws IOException {
int c;
tokenno++;
// Check for pushed-back token
if (this.pushbackToken != EOF) {
int result = this.pushbackToken;
this.pushbackToken = EOF;
return result;
}
// Eat whitespace, possibly sensitive to newlines.
do {
c = in.read();
if (c == '\n')
if ((flags & TSF_NEWLINES) != 0)
break;
} while (isJSSpace(c) || c == '\n');
if (c == EOF_CHAR)
return EOF;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = in.read();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
c = '\\';
in.unread();
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
reportSyntaxError("msg.invalid.escape", null);
return ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = in.read();
if (c == '\\') {
c = in.read();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
} else {
if (!Character.isJavaIdentifierPart((char)c)) {
break;
}
addToString(c);
}
}
}
in.unread();
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != EOF) {
if (result != RESERVED) {
return result;
}
else if (!Context.getContext().hasFeature(
Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER))
{
return result;
}
else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript standard,
// treat it as name but issue warning
Object[] errArgs = { str };
reportSyntaxWarning("msg.reserved.keyword", errArgs);
}
}
}
this.string = str;
return NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(in.peek()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = in.read();
if (c == 'x' || c == 'X') {
base = 16;
c = in.read();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= xDigitToInt(c)) {
addToString(c);
c = in.read();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
Object[] errArgs = { c == '8' ? "8" : "9" };
reportSyntaxWarning("msg.bad.octal.literal", errArgs);
base = 10;
}
addToString(c);
c = in.read();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = in.read();
if (c == '+' || c == '-') {
addToString(c);
c = in.read();
}
if (!isDigit(c)) {
reportSyntaxError("msg.missing.exponent", null);
return ERROR;
}
do {
addToString(c);
c = in.read();
} while (isDigit(c));
}
}
in.unread();
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = (Double.valueOf(numString)).doubleValue();
}
catch (NumberFormatException ex) {
Object[] errArgs = { ex.getMessage() };
reportSyntaxError("msg.caught.nfe", errArgs);
return ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
int val = 0;
stringBufferTop = 0;
c = in.read();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.string.lit", null);
return ERROR;
}
if (c == '\\') {
// We've hit an escaped character
c = in.read();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u': {
/*
* Get 4 hex digits; if the u escape is not
* followed by 4 hex digits, use 'u' + the literal
* character sequence that follows.
*/
int escapeStart = stringBufferTop;
addToString('u');
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
} break;
case 'x': {
/* Get 2 hex digits, defaulting to 'x' + literal
* sequence, as above.
*/
c = in.read();
int escapeVal = xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = in.read();
escapeVal = (escapeVal << 4) | xDigitToInt(c);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
} break;
default: if ('0' <= c && c < '8') {
val = c - '0';
c = in.read();
if ('0' <= c && c < '8') {
val = 8 * val + c - '0';
c = in.read();
if ('0' <= c && c < '8' && val <= 037) {
// c is 3rd char of octal sequence only if
// the resulting val <= 0377
val = 8 * val + c - '0';
c = in.read();
}
}
in.unread();
c = val;
}
}
}
addToString(c);
c = in.read();
}
this.string = getStringFromBuffer();
return STRING;
}
switch (c)
{
case '\n': return EOL;
case ';': return SEMI;
case '[': return LB;
case ']': return RB;
case '{': return LC;
case '}': return RC;
case '(': return LP;
case ')': return RP;
case ',': return COMMA;
case '?': return HOOK;
case ':': return COLON;
case '.': return DOT;
case '|':
if (in.match('|')) {
return OR;
} else if (in.match('=')) {
this.op = BITOR;
return ASSIGN;
} else {
return BITOR;
}
case '^':
if (in.match('=')) {
this.op = BITXOR;
return ASSIGN;
} else {
return BITXOR;
}
case '&':
if (in.match('&')) {
return AND;
} else if (in.match('=')) {
this.op = BITAND;
return ASSIGN;
} else {
return BITAND;
}
case '=':
if (in.match('=')) {
if (in.match('='))
this.op = SHEQ;
else
this.op = EQ;
return EQOP;
} else {
this.op = NOP;
return ASSIGN;
}
case '!':
if (in.match('=')) {
if (in.match('='))
this.op = SHNE;
else
this.op = NE;
return EQOP;
} else {
this.op = NOT;
return UNARYOP;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (in.match('!')) {
if (in.match('-')) {
if (in.match('-')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken(); // in place of 'goto retry'
}
in.unread();
}
in.unread();
}
if (in.match('<')) {
if (in.match('=')) {
this.op = LSH;
return ASSIGN;
} else {
this.op = LSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = LE;
return RELOP;
} else {
this.op = LT;
return RELOP;
}
}
case '>':
if (in.match('>')) {
if (in.match('>')) {
if (in.match('=')) {
this.op = URSH;
return ASSIGN;
} else {
this.op = URSH;
return SHOP;
}
} else {
if (in.match('=')) {
this.op = RSH;
return ASSIGN;
} else {
this.op = RSH;
return SHOP;
}
}
} else {
if (in.match('=')) {
this.op = GE;
return RELOP;
} else {
this.op = GT;
return RELOP;
}
}
case '*':
if (in.match('=')) {
this.op = MUL;
return ASSIGN;
} else {
return MUL;
}
case '/':
// is it a // comment?
if (in.match('/')) {
while ((c = in.read()) != EOF_CHAR && c != '\n')
/* skip to end of line */;
in.unread();
return getToken();
}
if (in.match('*')) {
while ((c = in.read()) != -1 &&
!(c == '*' && in.match('/'))) {
; // empty loop body
}
if (c == EOF_CHAR) {
reportSyntaxError("msg.unterminated.comment", null);
return ERROR;
}
return getToken(); // `goto retry'
}
// is it a regexp?
if ((flags & TSF_REGEXP) != 0) {
stringBufferTop = 0;
while ((c = in.read()) != '/') {
if (c == '\n' || c == EOF_CHAR) {
in.unread();
reportSyntaxError("msg.unterminated.re.lit", null);
return ERROR;
}
if (c == '\\') {
addToString(c);
c = in.read();
}
addToString(c);
}
int reEnd = stringBufferTop;
while (true) {
if (in.match('g'))
addToString('g');
else if (in.match('i'))
addToString('i');
else if (in.match('m'))
addToString('m');
else
break;
}
if (isAlpha(in.peek())) {
reportSyntaxError("msg.invalid.re.flag", null);
return ERROR;
}
this.string = new String(stringBuffer, 0, reEnd);
this.regExpFlags = new String(stringBuffer, reEnd,
stringBufferTop - reEnd);
return REGEXP;
}
if (in.match('=')) {
this.op = DIV;
return ASSIGN;
} else {
return DIV;
}
case '%':
this.op = MOD;
if (in.match('=')) {
return ASSIGN;
} else {
return MOD;
}
case '~':
this.op = BITNOT;
return UNARYOP;
case '+':
case '-':
if (in.match('=')) {
if (c == '+') {
this.op = ADD;
return ASSIGN;
} else {
this.op = SUB;
return ASSIGN;
}
} else if (in.match((char) c)) {
if (c == '+') {
return INC;
} else {
return DEC;
}
} else if (c == '-') {
return SUB;
} else {
return ADD;
}
default:
reportSyntaxError("msg.illegal.character", null);
return ERROR;
}
}
|
diff --git a/src/main/java/net/ae97/totalpermissions/permission/util/PermissionUtility.java b/src/main/java/net/ae97/totalpermissions/permission/util/PermissionUtility.java
index 1575dc0..c50ea78 100644
--- a/src/main/java/net/ae97/totalpermissions/permission/util/PermissionUtility.java
+++ b/src/main/java/net/ae97/totalpermissions/permission/util/PermissionUtility.java
@@ -1,89 +1,91 @@
/*
* Copyright (C) 2013 AE97
*
* 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 net.ae97.totalpermissions.permission.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
/**
* @author Lord_Ralex
* @version 0.1
* @since 0.1
*/
public class PermissionUtility {
/**
* Provides a list of all perms given by using '*'. This will only look at
* registered permissions made by plugins.
*
* @return List of perms given by '*'
*
* @since 0.1
*/
public static List<String> handleWildcard() {
return handleWildcard(false);
}
/**
* Provides a list of all perms given by using '*' or '**'. This will only
* look at registered permissions made by plugins.
*
* @param isAll True if '**', false for '*'
*
* @return List of perms given
*
* @since 0.1
*/
public static List<String> handleWildcard(boolean isAll) {
List<String> perms = new ArrayList<String>();
Set<Permission> permT = Bukkit.getPluginManager().getPermissions();
for (Permission permTest : permT) {
- if (permTest.getDefault() != PermissionDefault.FALSE) {
+ if (permTest.getName().startsWith("totalpermissions")) {
+ continue;
+ } else if (permTest.getDefault() != PermissionDefault.FALSE) {
perms.add(permTest.getName());
} else if (isAll) {
perms.add(permTest.getName());
}
}
return perms;
}
/**
* Gets a list of the permissions for a given list of commands. This list
* may not be in the exact order and may not contain the correct perm or may
* not be the same size.
*
* @param commands List of commands to get perms for
* @return List of perms for those commands
*
* @since 0.1
*/
public static List<String> getPermsForCommands(List<String> commands) {
List<String> perms = new ArrayList<String>();
for (String command : commands) {
Command cmd = Bukkit.getPluginCommand(command);
if (cmd != null) {
perms.add(cmd.getPermission());
}
}
return perms;
}
}
| true | true | public static List<String> handleWildcard(boolean isAll) {
List<String> perms = new ArrayList<String>();
Set<Permission> permT = Bukkit.getPluginManager().getPermissions();
for (Permission permTest : permT) {
if (permTest.getDefault() != PermissionDefault.FALSE) {
perms.add(permTest.getName());
} else if (isAll) {
perms.add(permTest.getName());
}
}
return perms;
}
| public static List<String> handleWildcard(boolean isAll) {
List<String> perms = new ArrayList<String>();
Set<Permission> permT = Bukkit.getPluginManager().getPermissions();
for (Permission permTest : permT) {
if (permTest.getName().startsWith("totalpermissions")) {
continue;
} else if (permTest.getDefault() != PermissionDefault.FALSE) {
perms.add(permTest.getName());
} else if (isAll) {
perms.add(permTest.getName());
}
}
return perms;
}
|
diff --git a/modules/org.restlet/src/org/restlet/security/Role.java b/modules/org.restlet/src/org/restlet/security/Role.java
index e14aeeb32..265d0fa1c 100644
--- a/modules/org.restlet/src/org/restlet/security/Role.java
+++ b/modules/org.restlet/src/org/restlet/security/Role.java
@@ -1,206 +1,206 @@
/**
* Copyright 2005-2011 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.security;
import java.security.Principal;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Application specific role. Common examples are "administrator", "user",
* "anonymous", "supervisor". Note that for reusability purpose, it is
* recommended that those role don't reflect an actual organization, but more
* the functional requirements of your application.
*
* @author Jerome Louvel
*/
public class Role implements Principal {
/**
* Unmodifiable role that covers all existing roles. Its name is "*" by
* convention.
*/
public static final Role ALL = new Role("*",
"Role that covers all existing roles.") {
@Override
public void setDescription(String description) {
throw new IllegalStateException("Unmodifiable role");
}
@Override
public void setName(String name) {
throw new IllegalStateException("Unmodifiable role");
}
};
/** The modifiable list of child roles. */
private final List<Role> childRoles;
/** The description. */
private volatile String description;
/** The name. */
private volatile String name;
/**
* Default constructor.
*/
public Role() {
this(null, null);
}
/**
* Constructor.
*
* @param name
* The name.
* @param description
* The description.
*/
public Role(String name, String description) {
this.name = name;
this.description = description;
this.childRoles = new CopyOnWriteArrayList<Role>();
}
@Override
- public boolean equals(Object arg0) {
+ public boolean equals(Object target) {
boolean result = false;
if (this.name == null) {
- return arg0 == null;
+ return target == null;
}
- if (arg0 instanceof Role) {
- Role r = (Role) arg0;
+ if (target instanceof Role) {
+ Role r = (Role) target;
// Test equality of names and child roles.
result = this.name.equals(r.getName())
&& getChildRoles().size() == r.getChildRoles().size();
if (result && !getChildRoles().isEmpty()) {
for (int i = 0; result && i < getChildRoles().size(); i++) {
result = getChildRoles().get(i).equals(
r.getChildRoles().get(i));
}
}
}
return result;
}
/**
* Returns the modifiable list of child roles.
*
* @return The modifiable list of child roles.
*/
public List<Role> getChildRoles() {
return childRoles;
}
/**
* Returns the description.
*
* @return The description.
*/
public String getDescription() {
return description;
}
/**
* Returns the name.
*
* @return The name.
*/
public String getName() {
return name;
}
@Override
public int hashCode() {
int result;
if (name == null) {
result = super.hashCode();
} else if (getChildRoles().isEmpty()) {
result = name.hashCode();
} else {
StringBuilder sb = new StringBuilder(name).append("(");
for (Role role : getChildRoles()) {
sb.append(role.hashCode()).append("-");
}
sb.append(")");
result = sb.toString().hashCode();
}
return result;
}
/**
* Sets the modifiable list of child roles. This method clears the current
* list and adds all entries in the parameter list.
*
* @param childRoles
* A list of child roles.
*/
public void setChildRoles(List<Role> childRoles) {
synchronized (getChildRoles()) {
if (childRoles != getChildRoles()) {
getChildRoles().clear();
if (childRoles != null) {
getChildRoles().addAll(childRoles);
}
}
}
}
/**
* Sets the description.
*
* @param description
* The description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Sets the name.
*
* @param name
* The name.
*/
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
}
| false | true | public boolean equals(Object arg0) {
boolean result = false;
if (this.name == null) {
return arg0 == null;
}
if (arg0 instanceof Role) {
Role r = (Role) arg0;
// Test equality of names and child roles.
result = this.name.equals(r.getName())
&& getChildRoles().size() == r.getChildRoles().size();
if (result && !getChildRoles().isEmpty()) {
for (int i = 0; result && i < getChildRoles().size(); i++) {
result = getChildRoles().get(i).equals(
r.getChildRoles().get(i));
}
}
}
return result;
}
| public boolean equals(Object target) {
boolean result = false;
if (this.name == null) {
return target == null;
}
if (target instanceof Role) {
Role r = (Role) target;
// Test equality of names and child roles.
result = this.name.equals(r.getName())
&& getChildRoles().size() == r.getChildRoles().size();
if (result && !getChildRoles().isEmpty()) {
for (int i = 0; result && i < getChildRoles().size(); i++) {
result = getChildRoles().get(i).equals(
r.getChildRoles().get(i));
}
}
}
return result;
}
|
diff --git a/src/jmt/gui/common/xml/XMLResultsReader.java b/src/jmt/gui/common/xml/XMLResultsReader.java
index 894ab1e..8589b22 100644
--- a/src/jmt/gui/common/xml/XMLResultsReader.java
+++ b/src/jmt/gui/common/xml/XMLResultsReader.java
@@ -1,278 +1,278 @@
/**
* Copyright (C) 2006, Laboratorio di Valutazione delle Prestazioni - Politecnico di Milano
* 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
*/
package jmt.gui.common.xml;
import jmt.common.xml.resources.XSDSchemaLoader;
import jmt.engine.QueueNet.SimConstants;
import jmt.gui.common.definitions.MeasureDefinition;
import jmt.gui.common.definitions.PAResultsModel;
import jmt.gui.common.definitions.StoredResultsModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
/**
* <p>Title: XML Results Reader</p>
* <p>Description: Reads stored results information from an XML file. This class is designed
* to work both with <code>XMLResultsWriter</code> and with engine's generated output files.
* Obviously the first one will provide much more informations.</p>
*
* @author Bertoli Marco
* Date: 3-ott-2005
* Time: 12.27.00
*/
public class XMLResultsReader implements XMLResultsConstants {
/**
* Loads stored GUI results into specified StoredResultsModel
* @param archiveName name of the archive to be opened
* @param model CommonModel where all loaded informations should be stored
*/
public static void loadGuiModel(StoredResultsModel model, File archiveName) {
Document doc = XMLReader.loadXML(archiveName.getAbsolutePath(), XSDSchemaLoader.loadSchema(XSDSchemaLoader.JSIM_GUI_RESULTS));
parseXML(doc, model);
}
/**
* Loads stored engine results into specified StoredResultsModel
* @param archiveName name of the archive to be opened
* @param model CommonModel where all loaded informations should be stored
*/
public static void loadModel(StoredResultsModel model, File archiveName) {
Document doc = XMLReader.loadXML(archiveName.getAbsolutePath(), XSDSchemaLoader.loadSchema(XSDSchemaLoader.JSIM_MODEL_RESULTS));
parseXML(doc, model);
}
/**
* Parses given <code>XMLResultsWriter</code> or engine's generated output XML Document.
* @param xml Document to be parsed
* @param model data model to be elaborated
*/
public static void parseXML(Document xml, MeasureDefinition model) {
parseXML(xml.getDocumentElement(), model);
}
/**
* Parses given <code>XMLResultsWriter</code> or engine's generated output XML Document.
* @param root xml document root to be parsed
* @param model data model to be elaborated
*/
public static void parseXML(Element root, MeasureDefinition model) {
if (model instanceof PAResultsModel) {
if (root.getNodeName().equals(XML_DOCUMENT_ROOT)) {
setMeasures(root, (PAResultsModel)model);
}
}
else {
if (root.getNodeName().equals(XML_DOCUMENT_ROOT)) {
// XMLResultsWriter output file
setMeasures(root, (StoredResultsModel)model);
}
else if (root.getNodeName().equals(XML_DOCUMENT_O_ROOT)){
// Engine's output file
setEngineMeasures(root, (StoredResultsModel)model);
}
}
}
/**
* Loads measures data from saved XML document. Used only for parametric
* analysis results.
* @param root root element of xml document
* @param model data structure
*/
private static void setMeasures(Element root, PAResultsModel model) {
NodeList measures = root.getElementsByTagName(XML_E_MEASURE);
for (int i=0; i<measures.getLength(); i++) {
Element current = (Element)measures.item(i);
String measureName = current.getAttribute(XML_A_MEASURE_NAME);
// Adds its samples
NodeList samples = current.getElementsByTagName(XML_E_SAMPLE);
model.addMeasure(
measureName,
current.getAttribute(XML_A_MEASURE_STATION),
current.getAttribute(XML_A_MEASURE_CLASS),
Double.parseDouble(current.getAttribute(XML_A_MEASURE_ALPHA)),
Double.parseDouble(current.getAttribute(XML_A_MEASURE_PRECISION)),
Integer.parseInt(current.getAttribute(XML_A_MEASURE_TYPE)),
current.getAttribute(XML_A_MEASURE_NODETYPE)
);
for (int j=0; j<samples.getLength(); j++) {
Element sample = (Element) samples.item(j);
double mean = 0;
double upper = 0;
double lower = 0;
boolean valid;
valid = Boolean.valueOf(sample.getAttribute(XML_A_SAMPLE_VALIDITY)).booleanValue();
mean = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_MEAN));
// If the sample was calculated with the requested precision simply parse
if (valid) {
upper = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_UPPERBOUND));
lower = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_LOWERBOUND));
}
//else check or fields equal to the String "Infinity"
else {
String u = sample.getAttribute(XML_A_SAMPLE_UPPERBOUND);
if (u.equals("Infinity")) upper = Double.POSITIVE_INFINITY;
else upper = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_UPPERBOUND));
String l = sample.getAttribute(XML_A_SAMPLE_LOWERBOUND);
if (l.equals("Infinity")) lower = Double.POSITIVE_INFINITY;
else lower = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_LOWERBOUND));
}
model.addSample(measureName,lower,mean,upper,valid);
}
}
}
/**
* Loads measures data from saved XML document
* @param root root element of xml document
* @param model data structure
*/
private static void setMeasures(Element root, StoredResultsModel model) {
double polling = Double.parseDouble(root.getAttribute(XML_A_ROOT_POLLING));
model.setPollingInterval(polling);
NodeList measures = root.getElementsByTagName(XML_E_MEASURE);
for (int i=0; i<measures.getLength(); i++) {
Element current = (Element)measures.item(i);
String measureName = current.getAttribute(XML_A_MEASURE_NAME);
// Add measure
model.addMeasure(
measureName,
current.getAttribute(XML_A_MEASURE_STATION),
current.getAttribute(XML_A_MEASURE_CLASS),
Double.parseDouble(current.getAttribute(XML_A_MEASURE_ALPHA)),
Double.parseDouble(current.getAttribute(XML_A_MEASURE_PRECISION)),
Integer.parseInt(current.getAttribute(XML_A_MEASURE_SAMPLES)),
Integer.parseInt(current.getAttribute(XML_A_MEASURE_STATE)),
Integer.parseInt(current.getAttribute(XML_A_MEASURE_TYPE)),
current.getAttribute(XML_A_MEASURE_NODETYPE)
);
// Adds its samples
NodeList samples = current.getElementsByTagName(XML_E_SAMPLE);
for (int j=0; j<samples.getLength(); j++) {
Element sample = (Element) samples.item(j);
double mean = 0;
double upper = 0;
double lower = 0;
mean = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_MEAN));
// Gets upperBound if specified
if (sample.getAttribute(XML_A_SAMPLE_UPPERBOUND) != null &&
sample.getAttribute(XML_A_SAMPLE_UPPERBOUND) != "")
upper = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_UPPERBOUND));
// Gets lowerBound if specified
if (sample.getAttribute(XML_A_SAMPLE_LOWERBOUND) != null &&
sample.getAttribute(XML_A_SAMPLE_LOWERBOUND) != "")
lower = Double.parseDouble(sample.getAttribute(XML_A_SAMPLE_LOWERBOUND));
// Adds sample
model.addMeasureSample(measureName, mean, upper, lower);
}
}
}
/**
* Loads measures data from XML document generated by engine
* @param root root element of xml document
* @param model data structure
*/
private static void setEngineMeasures(Element root, StoredResultsModel model) {
NodeList measures = root.getElementsByTagName(XML_EO_MEASURE);
for (int i=0; i<measures.getLength(); i++) {
Element current = (Element)measures.item(i);
// Required elements
String stationName = current.getAttribute(XML_AO_MEASURE_STATION);
String className = current.getAttribute(XML_AO_MEASURE_CLASS);
String type = current.getAttribute(XML_AO_MEASURE_TYPE);
String success = current.getAttribute(XML_AO_MEASURE_SUCCESFUL);
boolean successful = success.toLowerCase().equals("true");
// Optional Elements
String attr;
attr = current.getAttribute(XML_AO_MEASURE_MEAN);
double mean = 0;
if (attr != null && attr != "")
mean = Double.parseDouble(attr);
String nodeType = current.getAttribute(XML_AO_MEASURE_NODETYPE);
attr = current.getAttribute(XML_AO_MEASURE_UPPER);
double upper = 0;
if (attr != null && attr != "")
upper = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_LOWER);
double lower = 0;
if (attr != null && attr != "")
lower = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_SAMPLES);
int samples = 0;
if (attr != null && attr != "")
samples = Integer.parseInt(attr);
attr = current.getAttribute(XML_AO_MEASURE_ALPHA);
double alpha = 0;
// Inverts alpha
if (attr != null && attr != "")
alpha = 1 - Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_PRECISION);
double precision = 0;
if (attr != null && attr != "")
precision = Double.parseDouble(attr);
// Gets measure state
int state;
if (samples == 0)
state = MeasureDefinition.MEASURE_NO_SAMPLES;
else if (successful)
state = MeasureDefinition.MEASURE_SUCCESS;
else
state = MeasureDefinition.MEASURE_FAILED;
// Creates unique measure name
String Name = stationName + "_" + className + "_" + type;
// Decodes measure type
String tmp = type.toLowerCase();
int numType = 0;
if (tmp.startsWith("queue") && tmp.endsWith("length"))
numType = SimConstants.QUEUE_LENGTH;
else if (tmp.startsWith("utilization"))
numType = SimConstants.UTILIZATION;
else if (tmp.startsWith("throughput"))
numType = SimConstants.THROUGHPUT;
else if (tmp.startsWith("response") && tmp.endsWith("time"))
numType = SimConstants.RESPONSE_TIME;
else if (tmp.startsWith("residence") && tmp.endsWith("time"))
numType = SimConstants.RESIDENCE_TIME;
else if (tmp.startsWith("queue") && tmp.endsWith("time"))
numType = SimConstants.QUEUE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("time"))
numType = SimConstants.SYSTEM_RESPONSE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("throughput"))
numType = SimConstants.SYSTEM_THROUGHPUT;
else if (tmp.startsWith("customer") && tmp.endsWith("number"))
numType = SimConstants.SYSTEM_JOB_NUMBER;
- else if (type.startsWith("drop") && type.endsWith("rate"))
+ else if (tmp.startsWith("drop") && tmp.endsWith("rate"))
numType = SimConstants.DROP_RATE;
- else if (type.startsWith("system") && type.endsWith("rate"))
+ else if (tmp.startsWith("system") && tmp.endsWith("rate"))
numType = SimConstants.SYSTEM_DROP_RATE;
// Adds loaded informations into model data structure
model.addMeasure(Name, stationName, className, alpha, precision, samples, state, numType, nodeType);
model.addMeasureSample(Name, mean, upper, lower);
}
}
}
| false | true | private static void setEngineMeasures(Element root, StoredResultsModel model) {
NodeList measures = root.getElementsByTagName(XML_EO_MEASURE);
for (int i=0; i<measures.getLength(); i++) {
Element current = (Element)measures.item(i);
// Required elements
String stationName = current.getAttribute(XML_AO_MEASURE_STATION);
String className = current.getAttribute(XML_AO_MEASURE_CLASS);
String type = current.getAttribute(XML_AO_MEASURE_TYPE);
String success = current.getAttribute(XML_AO_MEASURE_SUCCESFUL);
boolean successful = success.toLowerCase().equals("true");
// Optional Elements
String attr;
attr = current.getAttribute(XML_AO_MEASURE_MEAN);
double mean = 0;
if (attr != null && attr != "")
mean = Double.parseDouble(attr);
String nodeType = current.getAttribute(XML_AO_MEASURE_NODETYPE);
attr = current.getAttribute(XML_AO_MEASURE_UPPER);
double upper = 0;
if (attr != null && attr != "")
upper = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_LOWER);
double lower = 0;
if (attr != null && attr != "")
lower = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_SAMPLES);
int samples = 0;
if (attr != null && attr != "")
samples = Integer.parseInt(attr);
attr = current.getAttribute(XML_AO_MEASURE_ALPHA);
double alpha = 0;
// Inverts alpha
if (attr != null && attr != "")
alpha = 1 - Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_PRECISION);
double precision = 0;
if (attr != null && attr != "")
precision = Double.parseDouble(attr);
// Gets measure state
int state;
if (samples == 0)
state = MeasureDefinition.MEASURE_NO_SAMPLES;
else if (successful)
state = MeasureDefinition.MEASURE_SUCCESS;
else
state = MeasureDefinition.MEASURE_FAILED;
// Creates unique measure name
String Name = stationName + "_" + className + "_" + type;
// Decodes measure type
String tmp = type.toLowerCase();
int numType = 0;
if (tmp.startsWith("queue") && tmp.endsWith("length"))
numType = SimConstants.QUEUE_LENGTH;
else if (tmp.startsWith("utilization"))
numType = SimConstants.UTILIZATION;
else if (tmp.startsWith("throughput"))
numType = SimConstants.THROUGHPUT;
else if (tmp.startsWith("response") && tmp.endsWith("time"))
numType = SimConstants.RESPONSE_TIME;
else if (tmp.startsWith("residence") && tmp.endsWith("time"))
numType = SimConstants.RESIDENCE_TIME;
else if (tmp.startsWith("queue") && tmp.endsWith("time"))
numType = SimConstants.QUEUE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("time"))
numType = SimConstants.SYSTEM_RESPONSE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("throughput"))
numType = SimConstants.SYSTEM_THROUGHPUT;
else if (tmp.startsWith("customer") && tmp.endsWith("number"))
numType = SimConstants.SYSTEM_JOB_NUMBER;
else if (type.startsWith("drop") && type.endsWith("rate"))
numType = SimConstants.DROP_RATE;
else if (type.startsWith("system") && type.endsWith("rate"))
numType = SimConstants.SYSTEM_DROP_RATE;
// Adds loaded informations into model data structure
model.addMeasure(Name, stationName, className, alpha, precision, samples, state, numType, nodeType);
model.addMeasureSample(Name, mean, upper, lower);
}
}
| private static void setEngineMeasures(Element root, StoredResultsModel model) {
NodeList measures = root.getElementsByTagName(XML_EO_MEASURE);
for (int i=0; i<measures.getLength(); i++) {
Element current = (Element)measures.item(i);
// Required elements
String stationName = current.getAttribute(XML_AO_MEASURE_STATION);
String className = current.getAttribute(XML_AO_MEASURE_CLASS);
String type = current.getAttribute(XML_AO_MEASURE_TYPE);
String success = current.getAttribute(XML_AO_MEASURE_SUCCESFUL);
boolean successful = success.toLowerCase().equals("true");
// Optional Elements
String attr;
attr = current.getAttribute(XML_AO_MEASURE_MEAN);
double mean = 0;
if (attr != null && attr != "")
mean = Double.parseDouble(attr);
String nodeType = current.getAttribute(XML_AO_MEASURE_NODETYPE);
attr = current.getAttribute(XML_AO_MEASURE_UPPER);
double upper = 0;
if (attr != null && attr != "")
upper = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_LOWER);
double lower = 0;
if (attr != null && attr != "")
lower = Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_SAMPLES);
int samples = 0;
if (attr != null && attr != "")
samples = Integer.parseInt(attr);
attr = current.getAttribute(XML_AO_MEASURE_ALPHA);
double alpha = 0;
// Inverts alpha
if (attr != null && attr != "")
alpha = 1 - Double.parseDouble(attr);
attr = current.getAttribute(XML_AO_MEASURE_PRECISION);
double precision = 0;
if (attr != null && attr != "")
precision = Double.parseDouble(attr);
// Gets measure state
int state;
if (samples == 0)
state = MeasureDefinition.MEASURE_NO_SAMPLES;
else if (successful)
state = MeasureDefinition.MEASURE_SUCCESS;
else
state = MeasureDefinition.MEASURE_FAILED;
// Creates unique measure name
String Name = stationName + "_" + className + "_" + type;
// Decodes measure type
String tmp = type.toLowerCase();
int numType = 0;
if (tmp.startsWith("queue") && tmp.endsWith("length"))
numType = SimConstants.QUEUE_LENGTH;
else if (tmp.startsWith("utilization"))
numType = SimConstants.UTILIZATION;
else if (tmp.startsWith("throughput"))
numType = SimConstants.THROUGHPUT;
else if (tmp.startsWith("response") && tmp.endsWith("time"))
numType = SimConstants.RESPONSE_TIME;
else if (tmp.startsWith("residence") && tmp.endsWith("time"))
numType = SimConstants.RESIDENCE_TIME;
else if (tmp.startsWith("queue") && tmp.endsWith("time"))
numType = SimConstants.QUEUE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("time"))
numType = SimConstants.SYSTEM_RESPONSE_TIME;
else if (tmp.startsWith("system") && tmp.endsWith("throughput"))
numType = SimConstants.SYSTEM_THROUGHPUT;
else if (tmp.startsWith("customer") && tmp.endsWith("number"))
numType = SimConstants.SYSTEM_JOB_NUMBER;
else if (tmp.startsWith("drop") && tmp.endsWith("rate"))
numType = SimConstants.DROP_RATE;
else if (tmp.startsWith("system") && tmp.endsWith("rate"))
numType = SimConstants.SYSTEM_DROP_RATE;
// Adds loaded informations into model data structure
model.addMeasure(Name, stationName, className, alpha, precision, samples, state, numType, nodeType);
model.addMeasureSample(Name, mean, upper, lower);
}
}
|
diff --git a/MythicDrops-Repair/src/main/java/net/nunnerycode/bukkit/mythicdrops/repair/MythicDropsRepair.java b/MythicDrops-Repair/src/main/java/net/nunnerycode/bukkit/mythicdrops/repair/MythicDropsRepair.java
index 9cb53403..6b6b1042 100644
--- a/MythicDrops-Repair/src/main/java/net/nunnerycode/bukkit/mythicdrops/repair/MythicDropsRepair.java
+++ b/MythicDrops-Repair/src/main/java/net/nunnerycode/bukkit/mythicdrops/repair/MythicDropsRepair.java
@@ -1,472 +1,472 @@
package net.nunnerycode.bukkit.mythicdrops.repair;
import com.comphenix.xp.rewards.xp.ExperienceManager;
import com.conventnunnery.libraries.config.CommentedConventYamlConfiguration;
import com.conventnunnery.libraries.config.ConventYamlConfiguration;
import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops;
import net.nunnerycode.java.libraries.cannonball.DebugPrinter;
import org.apache.commons.lang3.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class MythicDropsRepair extends JavaPlugin {
private DebugPrinter debugPrinter;
private Map<String, RepairItem> repairItemMap;
private Map<String, String> language;
private MythicDrops mythicDrops;
private ConventYamlConfiguration configYAML;
private boolean playSounds;
@Override
public void onDisable() {
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " disabled");
}
@Override
public void onEnable() {
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
mythicDrops = (MythicDrops) Bukkit.getPluginManager().getPlugin("MythicDrops");
repairItemMap = new HashMap<>();
language = new HashMap<>();
unpackConfigurationFiles(new String[]{"config.yml"}, false);
configYAML = new ConventYamlConfiguration(new File(getDataFolder(), "config.yml"),
YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version"));
configYAML.options().updateOnLoad(true);
configYAML.options().backupOnUpdate(true);
configYAML.load();
ConfigurationSection messages = configYAML.getConfigurationSection("messages");
if (messages != null) {
for (String key : messages.getKeys(true)) {
if (messages.isConfigurationSection(key)) {
continue;
}
language.put("messages." + key, messages.getString(key, key));
}
}
playSounds = configYAML.getBoolean("play-sounds", true);
if (!configYAML.isConfigurationSection("repair-costs")) {
defaultRepairCosts();
}
ConfigurationSection costs = configYAML.getConfigurationSection("repair-costs");
for (String key : costs.getKeys(false)) {
if (!costs.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = costs.getConfigurationSection(key);
MaterialData matData = parseMaterialData(cs);
String itemName = cs.getString("item-name");
List<String> itemLore = cs.getStringList("item-lore");
List<RepairCost> costList = new ArrayList<>();
ConfigurationSection costsSection = cs.getConfigurationSection("costs");
for (String costKey : costsSection.getKeys(false)) {
if (!costsSection.isConfigurationSection(costKey)) {
continue;
}
ConfigurationSection costSection = costsSection.getConfigurationSection(costKey);
MaterialData itemCost = parseMaterialData(costSection);
int experienceCost = costSection.getInt("experience-cost", 0);
int priority = costSection.getInt("priority", 0);
int amount = costSection.getInt("amount", 1);
double repairPerCost = costSection.getDouble("repair-per-cost", 0.1);
String costName = costSection.getString("item-name");
List<String> costLore = costSection.getStringList("item-lore");
RepairCost rc = new RepairCost(costKey, priority, experienceCost, repairPerCost, amount, itemCost,
costName, costLore);
costList.add(rc);
}
RepairItem ri = new RepairItem(key, matData, itemName, itemLore);
ri.addRepairCosts(costList.toArray(new RepairCost[costList.size()]));
repairItemMap.put(ri.getName(), ri);
}
debugPrinter.debug(Level.INFO, "Loaded repair items: " + repairItemMap.keySet().size());
Bukkit.getPluginManager().registerEvents(new RepairListener(this), this);
debugPrinter.debug(Level.INFO, "v" + getDescription().getVersion() + " enabled");
}
private void unpackConfigurationFiles(String[] configurationFiles, boolean overwrite) {
for (String s : configurationFiles) {
YamlConfiguration yc = CommentedConventYamlConfiguration.loadConfiguration(getResource(s));
try {
File f = new File(getDataFolder(), s);
if (!f.exists()) {
yc.save(f);
continue;
}
if (overwrite) {
yc.save(f);
}
} catch (IOException e) {
getLogger().warning("Could not unpack " + s);
}
}
}
private MaterialData parseMaterialData(ConfigurationSection cs) {
String materialDat = cs.getString("material-data", "");
String materialName = cs.getString("material-name", "");
if (materialDat.isEmpty()) {
return new MaterialData(Material.getMaterial(materialName));
}
int id = 0;
byte data = 0;
String[] split = materialDat.split(";");
switch (split.length) {
case 0:
break;
case 1:
id = NumberUtils.toInt(split[0], 0);
break;
default:
id = NumberUtils.toInt(split[0], 0);
data = NumberUtils.toByte(split[1], (byte) 0);
break;
}
return new MaterialData(id, data);
}
private void defaultRepairCosts() {
Material[] wood = {Material.WOOD_AXE, Material.WOOD_HOE, Material.WOOD_PICKAXE, Material.WOOD_SPADE,
Material.WOOD_SWORD, Material.BOW, Material.FISHING_ROD};
Material[] stone = {Material.STONE_AXE, Material.STONE_PICKAXE, Material.STONE_HOE, Material.STONE_SWORD,
Material.STONE_SPADE};
Material[] leather = {Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET,
Material.LEATHER_LEGGINGS};
Material[] chain = {Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_LEGGINGS};
Material[] iron = {Material.IRON_AXE, Material.IRON_BOOTS, Material.IRON_CHESTPLATE, Material.IRON_HELMET,
Material.IRON_LEGGINGS, Material.IRON_PICKAXE, Material.IRON_HOE, Material.IRON_SPADE,
Material.IRON_SWORD};
Material[] diamond = {Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_HELMET, Material.DIAMOND_HOE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_PICKAXE,
Material.DIAMOND_SPADE, Material.DIAMOND_SWORD};
Material[] gold = {Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
Material.GOLD_LEGGINGS, Material.GOLD_PICKAXE, Material.GOLD_HOE, Material.GOLD_SPADE,
Material.GOLD_SWORD};
for (Material m : wood) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.WOOD.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : stone) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.STONE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : gold) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.GOLD_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : iron) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : diamond) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.DIAMOND.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : leather) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.LEATHER.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : chain) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_FENCE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
- configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
+ configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
configYAML.save();
}
public String getLanguageString(String key, String[][] args) {
String s = getLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getLanguageString(String key) {
return language.containsKey(key) ? language.get(key) : key;
}
public String getFormattedLanguageString(String key, String[][] args) {
String s = getFormattedLanguageString(key);
for (String[] arg : args) {
s = s.replace(arg[0], arg[1]);
}
return s;
}
public String getFormattedLanguageString(String key) {
return getLanguageString(key).replace('&', '\u00A7').replace("\u00A7\u00A7", "&");
}
public RepairItem getRepairItem(ItemStack itemStack) {
String displayName = null;
List<String> lore = new ArrayList<>();
MaterialData materialData = itemStack.getData();
MaterialData baseData = new MaterialData(itemStack.getType().getId(), (byte) 0);
if (itemStack.hasItemMeta()) {
if (itemStack.getItemMeta().hasDisplayName()) {
displayName = itemStack.getItemMeta().getDisplayName();
}
if (itemStack.getItemMeta().hasLore()) {
lore = itemStack.getItemMeta().getLore();
}
}
for (RepairItem repItem : repairItemMap.values()) {
if (!repItem.getMaterialData().equals(materialData) && !repItem.getMaterialData().equals(baseData)) {
continue;
}
if (repItem.getItemName() != null && (displayName == null || !ChatColor.translateAlternateColorCodes('&',
repItem.getName()).equals(displayName))) {
continue;
}
if (repItem.getItemLore() != null && !repItem.getItemLore().isEmpty()) {
if (lore == null) {
continue;
}
List<String> coloredLore = new ArrayList<>();
for (String s : repItem.getItemLore()) {
coloredLore.add(ChatColor.translateAlternateColorCodes('&', s));
}
if (!coloredLore.equals(lore)) {
continue;
}
}
return repItem;
}
return null;
}
private RepairCost getRepairCost(RepairItem repairItem, List<RepairCost> repairCostsList, Inventory inventory) {
RepairCost repCost = null;
for (RepairCost repairCost : repairCostsList) {
ItemStack itemStack = repairItem.toItemStack(1);
if (inventory.containsAtLeast(itemStack, repairCost.getAmount())) {
if (repCost == null) {
repCost = repairCost;
continue;
}
if (repCost.getPriority() > repairCost.getPriority()) {
repCost = repairCost;
}
}
}
return repCost;
}
protected ItemStack repairItemStack(ItemStack itemStack, Inventory inventory) {
if (itemStack == null) {
return null;
}
ItemStack repaired = itemStack.clone();
RepairItem repairItem = getRepairItem(itemStack);
if (repairItem == null) {
return repaired;
}
List<RepairCost> repairCostList = repairItem.getRepairCosts();
if (repairCostList == null) {
return repaired;
}
RepairCost repairCost = getRepairCost(repairItem, repairCostList, inventory);
if (repairCost == null) {
return repaired;
}
if (!inventory.containsAtLeast(repairCost.toItemStack(1), repairCost.getAmount())) {
return repaired;
}
int amt = repairCost.getAmount();
while (amt > 0) {
int slot = inventory.first(repairCost.toItemStack(1));
ItemStack atSlot = inventory.getItem(slot);
int atSlotAmount = atSlot.getAmount();
if (atSlotAmount < amt) {
inventory.clear(slot);
amt -= atSlotAmount;
} else {
atSlot.setAmount(atSlotAmount - amt);
amt = 0;
}
}
short currentDurability = repaired.getDurability();
short newDurability = (short) (currentDurability - repaired.getType().getMaxDurability()
* repairCost.getRepairPercentagePerCost());
repaired.setDurability((short) Math.max(newDurability, 0));
for (HumanEntity humanEntity : inventory.getViewers()) {
if (humanEntity instanceof Player) {
((Player) humanEntity).updateInventory();
}
}
return repaired;
}
public static class RepairListener implements Listener {
private MythicDropsRepair repair;
private Map<String, ItemStack> repairing;
public RepairListener(MythicDropsRepair repair) {
this.repair = repair;
repairing = new HashMap<>();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockDamageEvent(BlockDamageEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getPlayer() == null) {
return;
}
if (event.getBlock().getType() != Material.ANVIL) {
return;
}
Player player = event.getPlayer();
if (repairing.containsKey(player.getName())) {
ItemStack oldInHand = repairing.get(player.getName());
ItemStack currentInHand = player.getItemInHand();
if (oldInHand.getType() != currentInHand.getType()) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
if (oldInHand.getDurability() == 0 || currentInHand.getDurability() == 0) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
RepairItem repairItem = repair.getRepairItem(currentInHand);
if (repairItem == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
List<RepairCost> repairCostList = repairItem.getRepairCosts();
if (repairCostList == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
RepairCost repairCost = repair.getRepairCost(repairItem, repairCostList, player.getInventory());
if (repairCost == null) {
player.sendMessage(repair.getFormattedLanguageString("messages.cannot-use"));
repairing.remove(player.getName());
return;
}
if (!player.getInventory().containsAtLeast(repairItem.toItemStack(1),
repairCost.getAmount())) {
player.sendMessage(repair.getFormattedLanguageString("messages.do-not-have", new String[][]{{"%material%",
repairItem.toItemStack(1).getType().name()}}));
repairing.remove(player.getName());
return;
}
ExperienceManager experienceManager = new ExperienceManager(player);
if (!experienceManager.hasExp(repairCost.getExperienceCost())) {
player.sendMessage(repair.getFormattedLanguageString("messages.do-not-have", new String[][]{{"%material%",
repairItem.toItemStack(1).getType().name()}}));
repairing.remove(player.getName());
return;
}
experienceManager.changeExp(-repairCost.getExperienceCost());
player.setItemInHand(repair.repairItemStack(oldInHand, player.getInventory()));
player.sendMessage(repair.getFormattedLanguageString("messages.success"));
repairing.remove(player.getName());
player.updateInventory();
if (repair.playSounds) {
player.playSound(event.getBlock().getLocation(), Sound.ANVIL_USE, 1.0F, 1.0F);
}
} else {
if (player.getItemInHand().getType() == Material.AIR) {
return;
}
repairing.put(player.getName(), player.getItemInHand());
player.sendMessage(repair.getFormattedLanguageString("messages.instructions"));
}
}
}
}
| false | true | private void defaultRepairCosts() {
Material[] wood = {Material.WOOD_AXE, Material.WOOD_HOE, Material.WOOD_PICKAXE, Material.WOOD_SPADE,
Material.WOOD_SWORD, Material.BOW, Material.FISHING_ROD};
Material[] stone = {Material.STONE_AXE, Material.STONE_PICKAXE, Material.STONE_HOE, Material.STONE_SWORD,
Material.STONE_SPADE};
Material[] leather = {Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET,
Material.LEATHER_LEGGINGS};
Material[] chain = {Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_LEGGINGS};
Material[] iron = {Material.IRON_AXE, Material.IRON_BOOTS, Material.IRON_CHESTPLATE, Material.IRON_HELMET,
Material.IRON_LEGGINGS, Material.IRON_PICKAXE, Material.IRON_HOE, Material.IRON_SPADE,
Material.IRON_SWORD};
Material[] diamond = {Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_HELMET, Material.DIAMOND_HOE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_PICKAXE,
Material.DIAMOND_SPADE, Material.DIAMOND_SWORD};
Material[] gold = {Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
Material.GOLD_LEGGINGS, Material.GOLD_PICKAXE, Material.GOLD_HOE, Material.GOLD_SPADE,
Material.GOLD_SWORD};
for (Material m : wood) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.WOOD.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : stone) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.STONE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : gold) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.GOLD_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : iron) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : diamond) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.DIAMOND.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : leather) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.LEATHER.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : chain) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_FENCE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
configYAML.save();
}
| private void defaultRepairCosts() {
Material[] wood = {Material.WOOD_AXE, Material.WOOD_HOE, Material.WOOD_PICKAXE, Material.WOOD_SPADE,
Material.WOOD_SWORD, Material.BOW, Material.FISHING_ROD};
Material[] stone = {Material.STONE_AXE, Material.STONE_PICKAXE, Material.STONE_HOE, Material.STONE_SWORD,
Material.STONE_SPADE};
Material[] leather = {Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET,
Material.LEATHER_LEGGINGS};
Material[] chain = {Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_HELMET,
Material.CHAINMAIL_LEGGINGS};
Material[] iron = {Material.IRON_AXE, Material.IRON_BOOTS, Material.IRON_CHESTPLATE, Material.IRON_HELMET,
Material.IRON_LEGGINGS, Material.IRON_PICKAXE, Material.IRON_HOE, Material.IRON_SPADE,
Material.IRON_SWORD};
Material[] diamond = {Material.DIAMOND_AXE, Material.DIAMOND_BOOTS, Material.DIAMOND_CHESTPLATE,
Material.DIAMOND_HELMET, Material.DIAMOND_HOE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_PICKAXE,
Material.DIAMOND_SPADE, Material.DIAMOND_SWORD};
Material[] gold = {Material.GOLD_AXE, Material.GOLD_BOOTS, Material.GOLD_CHESTPLATE, Material.GOLD_HELMET,
Material.GOLD_LEGGINGS, Material.GOLD_PICKAXE, Material.GOLD_HOE, Material.GOLD_SPADE,
Material.GOLD_SWORD};
for (Material m : wood) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.WOOD.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : stone) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.STONE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : gold) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.GOLD_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : iron) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_INGOT.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : diamond) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.DIAMOND.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : leather) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.LEATHER.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
for (Material m : chain) {
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".material-name", m.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.material-name", Material.IRON_FENCE.name());
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.priority", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_", "-") + ".costs.default.amount", 1);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.experience-cost", 0);
configYAML.set("repair-costs." + m.name().toLowerCase().replace("_",
"-") + ".costs.default.repair-per-cost", 0.1);
}
configYAML.save();
}
|
diff --git a/src/main/java/com/biasedbit/hotpotato/util/digest/DigestAuthChallengeResponse.java b/src/main/java/com/biasedbit/hotpotato/util/digest/DigestAuthChallengeResponse.java
index 70202c9..b46045e 100644
--- a/src/main/java/com/biasedbit/hotpotato/util/digest/DigestAuthChallengeResponse.java
+++ b/src/main/java/com/biasedbit/hotpotato/util/digest/DigestAuthChallengeResponse.java
@@ -1,207 +1,211 @@
/*
* Copyright 2010 Bruno de Carvalho
*
* 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.
*/
/*
* Copyright (c) 2009 WIT Software. All rights reserved.
*
* WIT Software Confidential and Proprietary information. It is strictly forbidden for 3rd parties to modify, decompile,
* disassemble, defeat, disable or circumvent any protection mechanism; to sell, license, lease, rent, redistribute or
* make accessible to any third party, whether for profit or without charge.
*
* carvalho 2009/06/03
*/
package com.biasedbit.hotpotato.util.digest;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Digest authentication challenge response.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class DigestAuthChallengeResponse {
// internal vars --------------------------------------------------------------------------------------------------
private final Map<String, String> properties;
// constructors ---------------------------------------------------------------------------------------------------
public DigestAuthChallengeResponse(Map<String, String> properties) {
this.properties = properties;
}
public DigestAuthChallengeResponse() {
this.properties = new HashMap<String, String>();
}
// public static methods ------------------------------------------------------------------------------------------
public static DigestAuthChallengeResponse createFromHeader(String header) throws ParseException {
return new DigestAuthChallengeResponse(DigestUtils.parseHeader(header));
}
public static boolean validateHeaderContent(DigestAuthChallengeResponse response) {
return ((response.properties.get(DigestUtils.SCHEME) != null) &&
(response.properties.get(DigestUtils.RESPONSE) != null) &&
(response.properties.get(DigestUtils.NONCE) == null) &&
(response.properties.get(DigestUtils.USERNAME) == null) &&
(response.properties.get(DigestUtils.URI) != null));
}
// public methods -------------------------------------------------------------------------------------------------
public String buildAsString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getScheme())
.append(" username=\"").append((this.getUsername()))
.append("\", nonce=\"").append(this.getNonce())
.append("\", uri=\"").append(this.getUri())
.append("\", response=\"").append(this.getResponse()).append('\"');
String tmp = this.getRealm();
if (tmp != null) {
builder.append(", realm=\"").append(tmp).append('\"');
}
tmp = this.getAlgorithm();
if (tmp != null) {
builder.append(", algorithm=").append(tmp);
}
tmp = this.getQop();
if (tmp != null) {
builder.append(", qop=").append(tmp)
.append(", cnonce=\"").append(this.getCnonce())
.append("\", nc=").append(this.getNonceCount());
}
+ tmp = this.getOpaque();
+ if (tmp != null) {
+ builder.append(", opaque=\"").append(tmp).append("\"");
+ }
return builder.toString();
}
public String getProperty(String key) {
return this.properties.get(key);
}
public void setProperty(String key, String value) {
this.properties.put(key, value);
}
// getters & setters ----------------------------------------------------------------------------------------------
public String getScheme() {
return this.properties.get(DigestUtils.SCHEME);
}
public void setScheme(String scheme) {
this.properties.put(DigestUtils.SCHEME, scheme);
}
public String getResponse() {
return this.properties.get(DigestUtils.RESPONSE);
}
public void setResponse(String response) {
this.properties.put(DigestUtils.RESPONSE, response);
}
public String getRealm() {
return this.properties.get(DigestUtils.REALM);
}
public void setRealm(String realm) {
this.properties.put(DigestUtils.REALM, realm);
}
public String getNonce() {
return this.properties.get(DigestUtils.NONCE);
}
public void setNonce(String nonce) {
this.properties.put(DigestUtils.NONCE, nonce);
}
public String getAlgorithm() {
return this.properties.get(DigestUtils.ALGORITHM);
}
public void setAlgorithm(String algorithm) {
this.properties.put(DigestUtils.ALGORITHM, algorithm);
}
public String getUsername() {
return this.properties.get(DigestUtils.USERNAME);
}
public void setUsername(String username) {
this.properties.put(DigestUtils.USERNAME, username);
}
public String getUri() {
return this.properties.get(DigestUtils.URI);
}
public void setUri(String uri) {
this.properties.put(DigestUtils.URI, uri);
}
public String getQop() {
return this.properties.get(DigestUtils.QOP);
}
public void setQop(String qop) {
this.properties.put(DigestUtils.QOP, qop);
}
public String getNonceCount() {
return this.properties.get(DigestUtils.NONCE_COUNT);
}
public void setNonceCount(int nonceCount) {
this.properties.put(DigestUtils.NONCE_COUNT, DigestUtils.toNonceCount(nonceCount));
}
public String getCnonce() {
return this.properties.get(DigestUtils.CLIENT_NONCE);
}
public void setCnonce(String cnonce) {
this.properties.put(DigestUtils.CLIENT_NONCE, cnonce);
}
public String getOpaque() {
return this.properties.get(DigestUtils.OPAQUE);
}
public void setOpaque(String opaque) {
this.properties.put(DigestUtils.OPAQUE, opaque);
}
public Map<String, String> getProperties() {
return Collections.unmodifiableMap(this.properties);
}
// low level overrides --------------------------------------------------------------------------------------------
@Override
public String toString() {
return new StringBuilder()
.append("DigestAuthChallengeResponse{")
.append("properties=").append(this.properties)
.append('}').toString();
}
}
| true | true | public String buildAsString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getScheme())
.append(" username=\"").append((this.getUsername()))
.append("\", nonce=\"").append(this.getNonce())
.append("\", uri=\"").append(this.getUri())
.append("\", response=\"").append(this.getResponse()).append('\"');
String tmp = this.getRealm();
if (tmp != null) {
builder.append(", realm=\"").append(tmp).append('\"');
}
tmp = this.getAlgorithm();
if (tmp != null) {
builder.append(", algorithm=").append(tmp);
}
tmp = this.getQop();
if (tmp != null) {
builder.append(", qop=").append(tmp)
.append(", cnonce=\"").append(this.getCnonce())
.append("\", nc=").append(this.getNonceCount());
}
return builder.toString();
}
| public String buildAsString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getScheme())
.append(" username=\"").append((this.getUsername()))
.append("\", nonce=\"").append(this.getNonce())
.append("\", uri=\"").append(this.getUri())
.append("\", response=\"").append(this.getResponse()).append('\"');
String tmp = this.getRealm();
if (tmp != null) {
builder.append(", realm=\"").append(tmp).append('\"');
}
tmp = this.getAlgorithm();
if (tmp != null) {
builder.append(", algorithm=").append(tmp);
}
tmp = this.getQop();
if (tmp != null) {
builder.append(", qop=").append(tmp)
.append(", cnonce=\"").append(this.getCnonce())
.append("\", nc=").append(this.getNonceCount());
}
tmp = this.getOpaque();
if (tmp != null) {
builder.append(", opaque=\"").append(tmp).append("\"");
}
return builder.toString();
}
|
diff --git a/components/bio-formats/src/loci/formats/in/FV1000Reader.java b/components/bio-formats/src/loci/formats/in/FV1000Reader.java
index 6d45f7387..1c96ed4f4 100644
--- a/components/bio-formats/src/loci/formats/in/FV1000Reader.java
+++ b/components/bio-formats/src/loci/formats/in/FV1000Reader.java
@@ -1,1416 +1,1418 @@
//
// FV1000Reader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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
*/
package loci.formats.in;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.ByteArrayHandle;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
import loci.formats.services.POIService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffParser;
/**
* FV1000Reader is the file format reader for Fluoview FV 1000 OIB and
* Fluoview FV 1000 OIF files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class FV1000Reader extends FormatReader {
// -- Constants --
public static final String FV1000_MAGIC_STRING_1 = "FileInformation";
public static final String FV1000_MAGIC_STRING_2 = "Acquisition Parameters";
public static final String[] OIB_SUFFIX = {"oib"};
public static final String[] OIF_SUFFIX = {"oif"};
public static final String[] FV1000_SUFFIXES = {"oib", "oif"};
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final int NUM_DIMENSIONS = 9;
/** ROI types. */
private static final int POINT = 2;
private static final int LINE = 3;
private static final int POLYLINE = 4;
private static final int RECTANGLE = 5;
private static final int CIRCLE = 6;
private static final int ELLIPSE = 7;
private static final int POLYGON = 8;
private static final int FREE_SHAPE = 9;
private static final int FREE_LINE = 10;
private static final int GRID = 11;
private static final int ARROW = 12;
private static final int COLOR_BAR = 13;
private static final int SCALE = 15;
// -- Fields --
private IniParser parser = new IniParser();
/** Names of every TIFF file to open. */
private Vector<String> tiffs;
/** Name of thumbnail file. */
private String thumbId;
/** Helper reader for thumbnail. */
private BMPReader thumbReader;
/** Used file list. */
private Vector<String> usedFiles;
/** Flag indicating this is an OIB dataset. */
private boolean isOIB;
/** File mappings for OIB file. */
private Hashtable<String, String> oibMapping;
private String[] code, size;
private Double[] pixelSize;
private int imageDepth;
private Vector<String> previewNames;
private String pixelSizeX, pixelSizeY;
private Vector<String> illuminations;
private Vector<Integer> wavelengths;
private String pinholeSize;
private String magnification, lensNA, objectiveName, workingDistance;
private String creationDate;
private Vector<ChannelData> channels;
private Vector<String> lutNames = new Vector<String>();
private Hashtable<Integer, String> filenames =
new Hashtable<Integer, String>();
private Hashtable<Integer, String> roiFilenames =
new Hashtable<Integer, String>();
private POIService poi;
private short[][][] lut;
private int lastChannel;
private double pixelSizeZ = 1, pixelSizeT = 1;
private String ptyStart = null, ptyEnd = null, ptyPattern = null, line = null;
// -- Constructor --
/** Constructs a new FV1000 reader. */
public FV1000Reader() {
super("Olympus FV1000", new String[] {"oib", "oif", "pty", "lut"});
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return checkSuffix(id, OIB_SUFFIX);
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, FV1000_SUFFIXES)) return true;
if (!open) return false; // not allowed to touch the file system
try {
Location oif = new Location(findOIFFile(name));
return oif.exists() && !oif.isDirectory() &&
checkSuffix(oif.getAbsolutePath(), "oif");
}
catch (IndexOutOfBoundsException e) { }
catch (NullPointerException e) { }
catch (FormatException e) { }
return false;
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 1024;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
String s = DataTools.stripString(stream.readString(blockLen));
return s.indexOf(FV1000_MAGIC_STRING_1) >= 0 ||
s.indexOf(FV1000_MAGIC_STRING_2) >= 0;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
String name = id.toLowerCase();
if (checkSuffix(name, FV1000_SUFFIXES)) {
return FormatTools.CANNOT_GROUP;
}
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
return lut == null ? null : lut[lastChannel];
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int file = no;
int image = 0;
String filename = null;
if (series == 0) {
file = no / (getImageCount() / tiffs.size());
image = no % (getImageCount() / tiffs.size());
if (file < tiffs.size()) filename = tiffs.get(file);
}
else {
file = no / (getImageCount() / previewNames.size());
image = no % (getImageCount() / previewNames.size());
if (file < previewNames.size()) {
filename = previewNames.get(file);
}
}
int[] coords = getZCTCoords(image);
lastChannel = coords[1];
if (filename == null) return buf;
RandomAccessInputStream plane = getFile(filename);
TiffParser tp = new TiffParser(plane);
IFDList ifds = tp.getIFDs();
if (image >= ifds.size()) return buf;
IFD ifd = ifds.get(image);
if (getSizeY() != ifd.getImageLength()) {
tp.getSamples(ifd, buf, x,
getIndex(coords[0], 0, coords[2]), w, 1);
}
else tp.getSamples(ifd, buf, x, y, w, h);
plane.close();
plane = null;
return buf;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (isOIB) {
return noPixels ? null : new String[] {currentId};
}
Vector<String> files = new Vector<String>();
if (usedFiles != null) {
for (String file : usedFiles) {
String f = file.toLowerCase();
if (!f.endsWith(".tif") && !f.endsWith(".tiff") && !f.endsWith(".bmp"))
{
files.add(file);
}
}
}
if (!noPixels) {
if (getSeries() == 0 && tiffs != null) {
files.addAll(tiffs);
}
else if (getSeries() == 1 && previewNames != null) {
files.addAll(previewNames);
}
}
return files.toArray(new String[0]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (thumbReader != null) thumbReader.close(fileOnly);
if (!fileOnly) {
tiffs = usedFiles = null;
thumbReader = null;
thumbId = null;
isOIB = false;
previewNames = null;
if (poi != null) poi.close();
poi = null;
lastChannel = 0;
wavelengths = null;
illuminations = null;
oibMapping = null;
code = size = null;
pixelSize = null;
imageDepth = 0;
pixelSizeX = pixelSizeY = null;
pinholeSize = null;
magnification = lensNA = objectiveName = workingDistance = null;
creationDate = null;
lut = null;
channels = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
isOIB = checkSuffix(id, OIB_SUFFIX);
if (isOIB) {
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(id));
}
// mappedOIF is used to distinguish between datasets that are being read
// directly (e.g. using ImageJ or showinf), and datasets that are being
// imported through omebf. In the latter case, the necessary directory
// structure is not preserved (only relative file names are stored in
// OMEIS), so we will need to use slightly different logic to build the
// list of associated files.
boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists();
wavelengths = new Vector<Integer>();
illuminations = new Vector<String>();
channels = new Vector<ChannelData>();
String oifName = null;
if (isOIB) {
oifName = mapOIBFiles();
}
else {
// make sure we have the OIF file, not a TIFF
if (!checkSuffix(id, OIF_SUFFIX)) {
currentId = findOIFFile(id);
initFile(currentId);
}
oifName = currentId;
}
String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath();
String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" :
oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1);
try {
getFile(oifName);
}
catch (IOException e) {
oifName = oifName.replaceAll(".oif", ".OIF");
}
// parse key/value pairs from the OIF file
code = new String[NUM_DIMENSIONS];
size = new String[NUM_DIMENSIONS];
pixelSize = new Double[NUM_DIMENSIONS];
previewNames = new Vector<String>();
boolean laserEnabled = true;
IniList f = getIniFile(oifName);
IniTable saveInfo = f.getTable("ProfileSaveInfo");
String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]);
for (String key : saveKeys) {
String value = saveInfo.get(key).toString();
value = sanitizeValue(value).trim();
if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
filenames.put(new Integer(key.substring(11)), value);
}
else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
try {
roiFilenames.put(new Integer(key.substring(11)), value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("PtyFileNameS")) ptyStart = value;
else if (key.equals("PtyFileNameE")) ptyEnd = value;
else if (key.equals("PtyFileNameT2")) ptyPattern = value;
else if (key.indexOf("Thumb") != -1) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
if (thumbId == null) thumbId = value.trim();
}
else if (key.startsWith("LutFileName")) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
lutNames.add(path + value);
}
else if (isPreviewName(value)) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
previewNames.add(path + value.trim());
}
}
for (int i=0; i<NUM_DIMENSIONS; i++) {
IniTable commonParams = f.getTable("Axis " + i + " Parameters Common");
code[i] = commonParams.get("AxisCode");
size[i] = commonParams.get("MaxSize");
double end = Double.parseDouble(commonParams.get("EndPosition"));
double start = Double.parseDouble(commonParams.get("StartPosition"));
pixelSize[i] = end - start;
}
IniTable referenceParams = f.getTable("Reference Image Parameter");
imageDepth = Integer.parseInt(referenceParams.get("ImageDepth"));
pixelSizeX = referenceParams.get("WidthConvertValue");
pixelSizeY = referenceParams.get("HeightConvertValue");
int index = 0;
IniTable laser = f.getTable("Laser " + index + " Parameters");
while (laser != null) {
laserEnabled = laser.get("Laser Enable").equals("1");
if (laserEnabled) {
wavelengths.add(new Integer(laser.get("LaserWavelength")));
}
creationDate = laser.get("ImageCaputreDate");
if (creationDate == null) {
creationDate = laser.get("ImageCaptureDate");
}
index++;
laser = f.getTable("Laser " + index + " Parameters");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
index = 1;
IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters");
while (guiChannel != null) {
ChannelData channel = new ChannelData();
channel.gain = new Double(guiChannel.get("AnalogPMTGain"));
channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage"));
channel.barrierFilter = guiChannel.get("BF Name");
channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0;
channel.name = guiChannel.get("CH Name");
channel.dyeName = guiChannel.get("DyeName");
channel.emissionFilter = guiChannel.get("EmissionDM Name");
channel.emWave = new Integer(guiChannel.get("EmissionWavelength"));
channel.excitationFilter = guiChannel.get("ExcitationDM Name");
channel.exWave = new Integer(guiChannel.get("ExcitationWavelength"));
channels.add(channel);
index++;
guiChannel = f.getTable("GUI Channel " + index + " Parameters");
}
index = 1;
IniTable channel = f.getTable("Channel " + index + " Parameters");
while (channel != null) {
String illumination = channel.get("LightType");
if (illumination == null) {
// Ignored
}
else if (illumination.indexOf("fluorescence") != -1) {
illumination = "Epifluorescence";
}
else if (illumination.indexOf("transmitted") != -1) {
illumination = "Transmitted";
}
else illumination = null;
illuminations.add(illumination);
index++;
channel = f.getTable("Channel " + index + " Parameters");
}
for (IniTable table : f) {
String tableName = table.get(IniTable.HEADER_KEY);
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta(tableName + " " + key, table.get(key));
}
}
}
LOGGER.info("Initializing helper readers");
// populate core metadata for preview series
if (previewNames.size() > 0) {
Vector<String> v = new Vector<String>();
for (int i=0; i<previewNames.size(); i++) {
String ss = previewNames.get(i);
ss = replaceExtension(ss, "pty", "tif");
if (ss.endsWith(".tif")) v.add(ss);
}
previewNames = v;
if (previewNames.size() > 0) {
core = new CoreMetadata[2];
core[0] = new CoreMetadata();
core[1] = new CoreMetadata();
IFDList ifds = null;
for (String previewName : previewNames) {
RandomAccessInputStream preview = getFile(previewName);
TiffParser tp = new TiffParser(preview);
ifds = tp.getIFDs();
preview.close();
core[1].imageCount += ifds.size();
}
core[1].sizeX = (int) ifds.get(0).getImageWidth();
core[1].sizeY = (int) ifds.get(0).getImageLength();
core[1].sizeZ = 1;
core[1].sizeT = 1;
core[1].sizeC = core[1].imageCount;
core[1].rgb = false;
int bits = ifds.get(0).getBitsPerSample()[0];
while ((bits % 8) != 0) bits++;
switch (bits) {
case 8:
core[1].pixelType = FormatTools.UINT8;
break;
case 16:
core[1].pixelType = FormatTools.UINT16;
break;
case 32:
core[1].pixelType = FormatTools.UINT32;
}
core[1].dimensionOrder = "XYCZT";
core[1].indexed = false;
}
}
core[0].imageCount = filenames.size();
tiffs = new Vector<String>(getImageCount());
thumbReader = new BMPReader();
thumbId = replaceExtension(thumbId, "pty", "bmp");
thumbId = sanitizeFile(thumbId, path);
LOGGER.info("Reading additional metadata");
// open each INI file (.pty extension) and build list of TIFF files
String tiffPath = null;
core[0].dimensionOrder = "XY";
for (int i=0, ii=0; ii<getImageCount(); i++, ii++) {
String file = filenames.get(new Integer(i));
while (file == null) file = filenames.get(new Integer(++i));
file = sanitizeFile(file, path);
if (file.indexOf(File.separator) != -1) {
tiffPath = file.substring(0, file.lastIndexOf(File.separator));
}
else tiffPath = file;
Location ptyFile = new Location(file);
if (!isOIB && !ptyFile.exists()) {
LOGGER.warn("Could not find .pty file ({}); guessing at the " +
"corresponding TIFF file.", file);
String tiff = replaceExtension(file, ".pty", ".tif");
tiffs.add(ii, tiff);
continue;
}
IniList pty = getIniFile(file);
IniTable fileInfo = pty.getTable("File Info");
file = sanitizeValue(fileInfo.get("DataName"));
if (!isPreviewName(file)) {
while (file.indexOf("GST") != -1) {
file = removeGST(file);
}
if (!mappedOIF) {
file = new Location(tiffPath, file).getAbsolutePath();
if (isOIB) {
file = file.substring(file.indexOf(File.separator));
}
}
tiffs.add(ii, file);
}
for (int dim=0; dim<NUM_DIMENSIONS; dim++) {
IniTable axis = pty.getTable("Axis " + dim + " Parameters");
if (axis == null) break;
boolean addAxis = Integer.parseInt(axis.get("Number")) > 1;
if (dim == 2) {
if (addAxis && getDimensionOrder().indexOf("C") == -1) {
core[0].dimensionOrder += "C";
}
}
else if (dim == 3) {
if (addAxis && getDimensionOrder().indexOf("Z") == -1) {
core[0].dimensionOrder += "Z";
}
}
else if (dim == 4) {
if (addAxis && getDimensionOrder().indexOf("T") == -1) {
core[0].dimensionOrder += "T";
}
}
}
IniTable acquisition = pty.getTable("Acquisition Parameters Common");
- magnification = acquisition.get("Magnification");
- lensNA = acquisition.get("ObjectiveLens NAValue");
- objectiveName = acquisition.get("ObjectiveLens Name");
- workingDistance = acquisition.get("ObjectiveLens WDValue");
- pinholeSize = acquisition.get("PinholeDiameter");
- String validBitCounts = acquisition.get("ValidBitCounts");
- if (validBitCounts != null) {
- core[0].bitsPerPixel = Integer.parseInt(validBitCounts);
+ if (acquisition != null) {
+ magnification = acquisition.get("Magnification");
+ lensNA = acquisition.get("ObjectiveLens NAValue");
+ objectiveName = acquisition.get("ObjectiveLens Name");
+ workingDistance = acquisition.get("ObjectiveLens WDValue");
+ pinholeSize = acquisition.get("PinholeDiameter");
+ String validBitCounts = acquisition.get("ValidBitCounts");
+ if (validBitCounts != null) {
+ core[0].bitsPerPixel = Integer.parseInt(validBitCounts);
+ }
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : pty) {
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta("Image " + ii + " : " + key, table.get(key));
}
}
}
}
if (tiffs.size() != getImageCount()) {
core[0].imageCount = tiffs.size();
}
usedFiles = new Vector<String>();
if (tiffPath != null) {
usedFiles.add(id);
if (!isOIB) {
Location dir = new Location(tiffPath);
if (!dir.exists()) {
throw new FormatException(
"Required directory " + tiffPath + " was not found.");
}
String[] list = mappedOIF ?
Location.getIdMap().keySet().toArray(new String[0]) : dir.list();
for (int i=0; i<list.length; i++) {
if (mappedOIF) usedFiles.add(list[i]);
else {
String p = new Location(tiffPath, list[i]).getAbsolutePath();
String check = p.toLowerCase();
if (!check.endsWith(".tif") && !check.endsWith(".pty") &&
!check.endsWith(".roi") && !check.endsWith(".lut") &&
!check.endsWith(".bmp"))
{
continue;
}
usedFiles.add(p);
}
}
}
}
LOGGER.info("Populating metadata");
// calculate axis sizes
int realChannels = 0;
for (int i=0; i<NUM_DIMENSIONS; i++) {
int ss = Integer.parseInt(size[i]);
if (pixelSize[i] == null) pixelSize[i] = 1.0;
if (code[i].equals("X")) core[0].sizeX = ss;
else if (code[i].equals("Y")) core[0].sizeY = ss;
else if (code[i].equals("Z")) {
core[0].sizeZ = ss;
// Z size stored in nm
pixelSizeZ =
Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000);
}
else if (code[i].equals("T")) {
core[0].sizeT = ss;
pixelSizeT =
Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000);
}
else if (ss > 0) {
if (getSizeC() == 0) core[0].sizeC = ss;
else core[0].sizeC *= ss;
if (code[i].equals("C")) realChannels = ss;
}
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
if (getImageCount() == getSizeC() && getSizeY() == 1) {
core[0].imageCount *= getSizeZ() * getSizeT();
}
else if (getImageCount() == getSizeC()) {
core[0].sizeZ = 1;
core[0].sizeT = 1;
}
if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) {
int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount();
if (diff == previewNames.size() || diff < 0) {
diff /= getSizeC();
if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff;
else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff;
}
else core[0].imageCount += diff;
}
if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T";
switch (imageDepth) {
case 1:
core[0].pixelType = FormatTools.UINT8;
break;
case 2:
core[0].pixelType = FormatTools.UINT16;
break;
case 4:
core[0].pixelType = FormatTools.UINT32;
break;
default:
throw new RuntimeException("Unsupported pixel depth: " + imageDepth);
}
// set up thumbnail file mapping
try {
RandomAccessInputStream thumb = getFile(thumbId);
byte[] b = new byte[(int) thumb.length()];
thumb.read(b);
thumb.close();
Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b));
thumbReader.setId("thumbnail.bmp");
for (int i=0; i<getSeriesCount(); i++) {
core[i].thumbSizeX = thumbReader.getSizeX();
core[i].thumbSizeY = thumbReader.getSizeY();
}
Location.mapFile("thumbnail.bmp", null);
}
catch (IOException e) {
LOGGER.debug("Could not read thumbnail", e);
}
// initialize lookup table
lut = new short[getSizeC()][3][65536];
byte[] buffer = new byte[65536 * 4];
int count = (int) Math.min(getSizeC(), lutNames.size());
for (int c=0; c<count; c++) {
try {
RandomAccessInputStream stream = getFile(lutNames.get(c));
stream.seek(stream.length() - 65536 * 4);
stream.read(buffer);
stream.close();
for (int q=0; q<buffer.length; q+=4) {
lut[c][0][q / 4] = buffer[q + 1];
lut[c][1][q / 4] = buffer[q + 2];
lut[c][2][q / 4] = buffer[q + 3];
}
}
catch (IOException e) {
LOGGER.debug("Could not read LUT", e);
lut = null;
break;
}
}
for (int i=0; i<getSeriesCount(); i++) {
core[i].rgb = false;
core[i].littleEndian = true;
core[i].interleaved = false;
core[i].metadataComplete = true;
core[i].indexed = false;
core[i].falseColor = false;
}
// populate MetadataStore
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
if (creationDate != null) {
creationDate = creationDate.replaceAll("'", "");
creationDate = DateTools.formatDate(creationDate, DATE_FORMAT);
}
for (int i=0; i<getSeriesCount(); i++) {
// populate Image data
store.setImageName("Series " + (i + 1), i);
if (creationDate != null) store.setImageCreationDate(creationDate, i);
else MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
populateMetadataStore(store, path);
}
}
private void populateMetadataStore(MetadataStore store, String path)
throws FormatException, IOException
{
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
for (int i=0; i<getSeriesCount(); i++) {
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
// populate Dimensions data
if (pixelSizeX != null) {
store.setDimensionsPhysicalSizeX(new Double(pixelSizeX), i, 0);
}
if (pixelSizeY != null) {
store.setDimensionsPhysicalSizeY(new Double(pixelSizeY), i, 0);
}
if (pixelSizeZ == Double.NEGATIVE_INFINITY ||
pixelSizeZ == Double.POSITIVE_INFINITY || getSizeZ() == 1)
{
pixelSizeZ = 0d;
}
if (pixelSizeT == Double.NEGATIVE_INFINITY ||
pixelSizeT == Double.POSITIVE_INFINITY || getSizeT() == 1)
{
pixelSizeT = 0d;
}
store.setDimensionsPhysicalSizeZ(pixelSizeZ, i, 0);
store.setDimensionsTimeIncrement(pixelSizeT, i, 0);
// populate LogicalChannel data
for (int c=0; c<core[i].sizeC; c++) {
if (c < illuminations.size()) {
store.setLogicalChannelIlluminationType(illuminations.get(c), i, c);
}
}
}
int channelIndex = 0;
for (ChannelData channel : channels) {
if (!channel.active) continue;
if (channelIndex >= getEffectiveSizeC()) break;
// populate Detector data
String detectorID = MetadataTools.createLSID("Detector", 0, channelIndex);
store.setDetectorID(detectorID, 0, channelIndex);
store.setDetectorSettingsDetector(detectorID, 0, channelIndex);
store.setDetectorGain(channel.gain, 0, channelIndex);
store.setDetectorVoltage(channel.voltage, 0, channelIndex);
store.setDetectorType("PMT", 0, channelIndex);
// populate LogicalChannel data
String filterSet = MetadataTools.createLSID("FilterSet", 0, channelIndex);
store.setLogicalChannelName(channel.name, 0, channelIndex);
String lightSourceID =
MetadataTools.createLSID("LightSource", 0, channelIndex);
store.setLightSourceSettingsLightSource(lightSourceID, 0, channelIndex);
if (channel.emWave.intValue() > 0) {
store.setLogicalChannelEmWave(channel.emWave, 0, channelIndex);
}
if (channel.exWave.intValue() > 0) {
store.setLogicalChannelExWave(channel.exWave, 0, channelIndex);
store.setLightSourceSettingsWavelength(channel.exWave, 0, channelIndex);
}
store.setLogicalChannelFilterSet(filterSet, 0, channelIndex);
// populate Filter data
if (channel.barrierFilter != null) {
String filterID = MetadataTools.createLSID("Filter", 0, channelIndex);
store.setFilterID(filterID, 0, channelIndex);
store.setFilterModel(channel.barrierFilter, 0, channelIndex);
if (channel.barrierFilter.indexOf("-") != -1) {
String[] emValues = channel.barrierFilter.split("-");
for (int i=0; i<emValues.length; i++) {
emValues[i] = emValues[i].replaceAll("\\D", "");
}
try {
store.setTransmittanceRangeCutIn(
new Integer(emValues[0]), 0, channelIndex);
store.setTransmittanceRangeCutOut(
new Integer(emValues[1]), 0, channelIndex);
}
catch (NumberFormatException e) { }
}
store.setLogicalChannelSecondaryEmissionFilter(
filterID, 0, channelIndex);
}
// populate FilterSet data
int emIndex = channelIndex * 2;
int exIndex = channelIndex * 2 + 1;
String emFilter = MetadataTools.createLSID("Dichroic", 0, emIndex);
String exFilter = MetadataTools.createLSID("Dichroic", 0, exIndex);
store.setFilterSetID(filterSet, 0, channelIndex);
store.setFilterSetDichroic(exFilter, 0, channelIndex);
// populate Dichroic data
store.setDichroicID(emFilter, 0, emIndex);
store.setDichroicModel(channel.emissionFilter, 0, emIndex);
store.setDichroicID(exFilter, 0, exIndex);
store.setDichroicModel(channel.excitationFilter, 0, exIndex);
// populate Laser data
store.setLightSourceID(lightSourceID, 0, channelIndex);
store.setLaserLaserMedium(channel.dyeName, 0, channelIndex);
if (channelIndex < wavelengths.size()) {
store.setLaserWavelength(
wavelengths.get(channelIndex), 0, channelIndex);
}
store.setLaserType("Unknown", 0, channelIndex);
channelIndex++;
}
// populate Objective data
if (lensNA != null) store.setObjectiveLensNA(new Double(lensNA), 0, 0);
store.setObjectiveModel(objectiveName, 0, 0);
if (magnification != null) {
int mag = (int) Float.parseFloat(magnification);
store.setObjectiveNominalMagnification(mag, 0, 0);
}
if (workingDistance != null) {
store.setObjectiveWorkingDistance(new Double(workingDistance), 0, 0);
}
store.setObjectiveCorrection("Unknown", 0, 0);
store.setObjectiveImmersion("Unknown", 0, 0);
// link Objective to Image using ObjectiveSettings
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setObjectiveSettingsObjective(objectiveID, 0);
int nextROI = -1;
// populate ROI data - there is one ROI file per plane
for (int i=0; i<roiFilenames.size(); i++) {
if (i >= getImageCount()) break;
String filename = roiFilenames.get(new Integer(i));
filename = sanitizeFile(filename, path);
nextROI = parseROIFile(filename, store, nextROI, i);
}
}
private int parseROIFile(String filename, MetadataStore store, int nextROI,
int plane) throws FormatException, IOException
{
int[] coordinates = getZCTCoords(plane);
IniList roiFile = getIniFile(filename);
boolean validROI = false;
int shape = -1;
int shapeType = -1;
String[] xc = null, yc = null;
int divide = 0;
int color = 0, fontSize = 0, lineWidth = 0, angle = 0;
String fontName = null, name = null;
for (IniTable table : roiFile) {
String tableName = table.get(IniTable.HEADER_KEY);
if (tableName.equals("ROIBase FileInformation")) {
try {
String roiName = table.get("Name").replaceAll("\"", "");
validROI = Integer.parseInt(roiName) > 1;
}
catch (NumberFormatException e) { validROI = false; }
if (!validROI) continue;
}
else if (tableName.equals("ROIBase Body")) {
shapeType = Integer.parseInt(table.get("SHAPE"));
divide = Integer.parseInt(table.get("DIVIDE"));
String[] fontAttributes = table.get("FONT").split(",");
fontName = fontAttributes[0];
fontSize = Integer.parseInt(fontAttributes[1]);
lineWidth = Integer.parseInt(table.get("LINEWIDTH"));
color = Integer.parseInt(table.get("FORECOLOR"));
name = table.get("NAME");
angle = Integer.parseInt(table.get("ANGLE"));
xc = table.get("X").split(",");
yc = table.get("Y").split(",");
int x = Integer.parseInt(xc[0]);
int width = xc.length > 1 ? Integer.parseInt(xc[1]) - x : 0;
int y = Integer.parseInt(yc[0]);
int height = yc.length > 1 ? Integer.parseInt(yc[1]) - y : 0;
if (width + x <= getSizeX() && height + y <= getSizeY()) {
shape++;
Integer zIndex = new Integer(coordinates[0]);
Integer tIndex = new Integer(coordinates[2]);
if (shape == 0) {
nextROI++;
store.setROIZ0(zIndex, 0, nextROI);
store.setROIZ1(zIndex, 0, nextROI);
store.setROIT0(tIndex, 0, nextROI);
store.setROIT1(tIndex, 0, nextROI);
}
store.setShapeTheZ(zIndex, 0, nextROI, shape);
store.setShapeTheT(tIndex, 0, nextROI, shape);
store.setShapeFontSize(fontSize, 0, nextROI, shape);
store.setShapeFontFamily(fontName, 0, nextROI, shape);
store.setShapeText(name, 0, nextROI, shape);
store.setShapeStrokeWidth(lineWidth, 0, nextROI, shape);
store.setShapeStrokeColor(String.valueOf(color), 0, nextROI, shape);
if (shapeType == POINT) {
store.setPointCx(xc[0], 0, nextROI, shape);
store.setPointCy(yc[0], 0, nextROI, shape);
}
else if (shapeType == GRID || shapeType == RECTANGLE) {
if (shapeType == RECTANGLE) divide = 1;
width /= divide;
height /= divide;
for (int row=0; row<divide; row++) {
for (int col=0; col<divide; col++) {
int realX = x + col * width;
int realY = y + row * height;
store.setRectX(String.valueOf(realX), 0, nextROI, shape);
store.setRectY(String.valueOf(realY), 0, nextROI, shape);
store.setRectWidth(String.valueOf(width), 0, nextROI, shape);
store.setRectHeight(String.valueOf(height), 0, nextROI, shape);
int centerX = realX + (width / 2);
int centerY = realY + (height / 2);
store.setRectTransform(String.format("rotate(%d %d %d)",
angle, centerX, centerY), 0, nextROI, shape);
if (row < divide - 1 || col < divide - 1) shape++;
}
}
}
else if (shapeType == LINE) {
store.setLineX1(String.valueOf(x), 0, nextROI, shape);
store.setLineY1(String.valueOf(y), 0, nextROI, shape);
store.setLineX2(String.valueOf(x + width), 0, nextROI, shape);
store.setLineY2(String.valueOf(y + height), 0, nextROI, shape);
int centerX = x + (width / 2);
int centerY = y + (height / 2);
store.setLineTransform(String.format("rotate(%d %d %d)",
angle, centerX, centerY), 0, nextROI, shape);
}
else if (shapeType == CIRCLE) {
int r = width / 2;
store.setCircleCx(String.valueOf(x + r), 0, nextROI, shape);
store.setCircleCy(String.valueOf(y + r), 0, nextROI, shape);
store.setCircleR(String.valueOf(r), 0, nextROI, shape);
}
else if (shapeType == ELLIPSE) {
int rx = width / 2;
int ry = height / 2;
store.setEllipseCx(String.valueOf(x + rx), 0, nextROI, shape);
store.setEllipseCy(String.valueOf(y + ry), 0, nextROI, shape);
store.setEllipseRx(String.valueOf(rx), 0, nextROI, shape);
store.setEllipseRy(String.valueOf(ry), 0, nextROI, shape);
store.setEllipseTransform(String.format("rotate(%d %d %d)",
angle, x + rx, y + ry), 0, nextROI, shape);
}
else if (shapeType == POLYGON || shapeType == FREE_SHAPE ||
shapeType == POLYLINE || shapeType == FREE_LINE)
{
StringBuffer points = new StringBuffer();
for (int point=0; point<xc.length; point++) {
points.append(xc[point]);
points.append(",");
points.append(yc[point]);
if (point < xc.length - 1) points.append(" ");
}
if (shapeType == POLYGON || shapeType == FREE_SHAPE) {
store.setPolygonPoints(points.toString(), 0, nextROI, shape);
store.setPolygonTransform("rotate(" + angle + ")", 0, nextROI,
shape);
}
else {
store.setPolylinePoints(points.toString(), 0, nextROI, shape);
store.setPolylineTransform("rotate(" + angle + ")", 0, nextROI,
shape);
}
}
}
}
}
return nextROI;
}
private void addPtyFiles() throws FormatException {
if (ptyStart != null && ptyEnd != null && ptyPattern != null) {
// FV1000 version 2 gives the first .pty file, the last .pty and
// the file name pattern. Version 1 lists each .pty file individually.
// pattern is typically 's_C%03dT%03d.pty'
// build list of block indexes
String[] prefixes = ptyPattern.split("%03d");
// get first and last numbers for each block
int[] first = scanFormat(ptyPattern, ptyStart);
int[] last = scanFormat(ptyPattern, ptyEnd);
int[] lengths = new int[prefixes.length - 1];
int totalFiles = 1;
for (int i=0; i<first.length; i++) {
lengths[i] = last[i] - first[i] + 1;
totalFiles *= lengths[i];
}
// add each .pty file
for (int file=0; file<totalFiles; file++) {
int[] pos = FormatTools.rasterToPosition(lengths, file);
StringBuffer pty = new StringBuffer();
for (int block=0; block<prefixes.length; block++) {
pty.append(prefixes[block]);
if (block < pos.length) {
String num = String.valueOf(pos[block] + 1);
for (int q=0; q<3 - num.length(); q++) {
pty.append("0");
}
pty.append(num);
}
}
filenames.put(new Integer(file), pty.toString());
}
}
}
// -- Helper methods --
private String findOIFFile(String baseFile) throws FormatException {
Location current = new Location(baseFile).getAbsoluteFile();
String parent = current.getParent();
Location tmp = new Location(parent).getParentFile();
parent = tmp.getAbsolutePath();
baseFile = current.getName();
if (baseFile == null || baseFile.indexOf("_") == -1) return null;
baseFile = baseFile.substring(0, baseFile.lastIndexOf("_"));
if (checkSuffix(current.getName(), "roi")) {
// ROI files have an extra underscore
baseFile = baseFile.substring(0, baseFile.lastIndexOf("_"));
}
baseFile += ".oif";
tmp = new Location(tmp, baseFile);
String oifFile = tmp.getAbsolutePath();
if (!tmp.exists()) {
oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF";
tmp = new Location(oifFile);
if (!tmp.exists()) {
// check in parent directory
if (parent.endsWith(File.separator)) {
parent = parent.substring(0, parent.length() - 1);
}
String dir = parent.substring(parent.lastIndexOf(File.separator));
dir = dir.substring(0, dir.lastIndexOf("."));
tmp = new Location(parent);
oifFile = new Location(tmp, dir).getAbsolutePath();
if (!new Location(oifFile).exists()) {
throw new FormatException("OIF file not found");
}
}
}
return oifFile;
}
private String mapOIBFiles() throws FormatException, IOException {
String oifName = null;
String infoFile = null;
Vector<String> list = poi.getDocumentList();
for (String name : list) {
if (name.endsWith("OibInfo.txt")) {
infoFile = name;
break;
}
}
if (infoFile == null) {
throw new FormatException("OibInfo.txt not found in " + currentId);
}
RandomAccessInputStream ras = poi.getDocumentStream(infoFile);
oibMapping = new Hashtable<String, String>();
// set up file name mappings
String s = DataTools.stripString(ras.readString((int) ras.length()));
ras.close();
String[] lines = s.split("\n");
// sort the lines to ensure that the
// directory key is before the file names
Arrays.sort(lines);
String directoryKey = null, directoryValue = null, key = null, value = null;
for (String line : lines) {
line = line.trim();
if (line.indexOf("=") != -1) {
key = line.substring(0, line.indexOf("="));
value = line.substring(line.indexOf("=") + 1);
if (directoryKey != null && directoryValue != null) {
value = value.replaceAll(directoryKey, directoryValue);
}
value = removeGST(value);
if (key.startsWith("Stream")) {
if (checkSuffix(value, OIF_SUFFIX)) oifName = value;
value = sanitizeFile(value, "");
if (directoryKey != null && value.startsWith(directoryValue)) {
oibMapping.put(value, "Root Entry" + File.separator +
directoryKey + File.separator + key);
}
else {
oibMapping.put(value, "Root Entry" + File.separator + key);
}
}
else if (key.startsWith("Storage")) {
directoryKey = key;
directoryValue = value;
}
}
}
s = null;
return oifName;
}
private String sanitizeValue(String value) {
String f = value.replaceAll("\"", "");
f = f.replace('\\', File.separatorChar);
f = f.replace('/', File.separatorChar);
while (f.indexOf("GST") != -1) {
f = removeGST(f);
}
return f;
}
private String sanitizeFile(String file, String path) {
String f = sanitizeValue(file);
if (!isOIB && path.equals("")) return f;
return path + File.separator + f;
}
private String removeGST(String s) {
if (s.indexOf("GST") != -1) {
String first = s.substring(0, s.indexOf("GST"));
int ndx = s.indexOf(File.separator) < s.indexOf("GST") ?
s.length() : s.indexOf(File.separator);
String last = s.substring(s.lastIndexOf("=", ndx) + 1);
return first + last;
}
return s;
}
private RandomAccessInputStream getFile(String name)
throws FormatException, IOException
{
if (isOIB) {
if (!name.startsWith(File.separator)) {
name = File.separator + name;
}
name = name.replace('\\', File.separatorChar);
name = name.replace('/', File.separatorChar);
return poi.getDocumentStream(oibMapping.get(name));
}
else return new RandomAccessInputStream(name);
}
private boolean isPreviewName(String name) {
// "-R" in the file name indicates that this is a preview image
int index = name.indexOf("-R");
return index == name.length() - 9;
}
private String replaceExtension(String name, String oldExt, String newExt) {
if (!name.endsWith("." + oldExt)) {
return name;
}
return name.substring(0, name.length() - oldExt.length()) + newExt;
}
/* Return the numbers in the given string matching %..d style patterns */
private static int[] scanFormat(String pattern, String string)
throws FormatException
{
Vector<Integer> percentOffsets = new Vector<Integer>();
int offset = -1;
for (;;) {
offset = pattern.indexOf('%', offset + 1);
if (offset < 0 || offset + 1 >= pattern.length()) {
break;
}
if (pattern.charAt(offset + 1) == '%') {
continue;
}
percentOffsets.add(new Integer(offset));
}
int[] result = new int[percentOffsets.size()];
int patternOffset = 0;
offset = 0;
for (int i=0; i<result.length; i++) {
int percent = percentOffsets.get(i).intValue();
if (!string.regionMatches(offset, pattern, patternOffset,
percent - patternOffset))
{
throw new FormatException("String '" + string +
"' does not match format '" + pattern + "'");
}
offset += percent - patternOffset;
patternOffset = percent;
int endOffset = offset;
while (endOffset < string.length() &&
Character.isDigit(string.charAt(endOffset)))
{
endOffset++;
}
result[i] = Integer.parseInt(string.substring(offset, endOffset));
offset = endOffset;
while (++patternOffset < pattern.length() &&
pattern.charAt(patternOffset - 1) != 'd')
{
; /* do nothing */
}
}
int remaining = pattern.length() - patternOffset;
if (string.length() - offset != remaining ||
!string.regionMatches(offset, pattern, patternOffset, remaining))
{
throw new FormatException("String '" + string +
"' does not match format '" + pattern + "'");
}
return result;
}
private IniList getIniFile(String filename)
throws FormatException, IOException
{
RandomAccessInputStream stream = getFile(filename);
stream.skipBytes(2);
String data = stream.readString((int) stream.length() - 2);
data = DataTools.stripString(data);
BufferedReader reader = new BufferedReader(new StringReader(data));
stream.close();
IniList list = parser.parseINI(reader);
// most of the values will be wrapped in double quotes
for (IniTable table : list) {
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
table.put(key, sanitizeValue(table.get(key)));
}
}
return list;
}
// -- Helper classes --
class ChannelData {
public boolean active;
public Double gain;
public Double voltage;
public String name;
public String emissionFilter;
public String excitationFilter;
public Integer emWave;
public Integer exWave;
public String dyeName;
public String barrierFilter;
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
isOIB = checkSuffix(id, OIB_SUFFIX);
if (isOIB) {
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(id));
}
// mappedOIF is used to distinguish between datasets that are being read
// directly (e.g. using ImageJ or showinf), and datasets that are being
// imported through omebf. In the latter case, the necessary directory
// structure is not preserved (only relative file names are stored in
// OMEIS), so we will need to use slightly different logic to build the
// list of associated files.
boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists();
wavelengths = new Vector<Integer>();
illuminations = new Vector<String>();
channels = new Vector<ChannelData>();
String oifName = null;
if (isOIB) {
oifName = mapOIBFiles();
}
else {
// make sure we have the OIF file, not a TIFF
if (!checkSuffix(id, OIF_SUFFIX)) {
currentId = findOIFFile(id);
initFile(currentId);
}
oifName = currentId;
}
String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath();
String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" :
oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1);
try {
getFile(oifName);
}
catch (IOException e) {
oifName = oifName.replaceAll(".oif", ".OIF");
}
// parse key/value pairs from the OIF file
code = new String[NUM_DIMENSIONS];
size = new String[NUM_DIMENSIONS];
pixelSize = new Double[NUM_DIMENSIONS];
previewNames = new Vector<String>();
boolean laserEnabled = true;
IniList f = getIniFile(oifName);
IniTable saveInfo = f.getTable("ProfileSaveInfo");
String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]);
for (String key : saveKeys) {
String value = saveInfo.get(key).toString();
value = sanitizeValue(value).trim();
if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
filenames.put(new Integer(key.substring(11)), value);
}
else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
try {
roiFilenames.put(new Integer(key.substring(11)), value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("PtyFileNameS")) ptyStart = value;
else if (key.equals("PtyFileNameE")) ptyEnd = value;
else if (key.equals("PtyFileNameT2")) ptyPattern = value;
else if (key.indexOf("Thumb") != -1) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
if (thumbId == null) thumbId = value.trim();
}
else if (key.startsWith("LutFileName")) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
lutNames.add(path + value);
}
else if (isPreviewName(value)) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
previewNames.add(path + value.trim());
}
}
for (int i=0; i<NUM_DIMENSIONS; i++) {
IniTable commonParams = f.getTable("Axis " + i + " Parameters Common");
code[i] = commonParams.get("AxisCode");
size[i] = commonParams.get("MaxSize");
double end = Double.parseDouble(commonParams.get("EndPosition"));
double start = Double.parseDouble(commonParams.get("StartPosition"));
pixelSize[i] = end - start;
}
IniTable referenceParams = f.getTable("Reference Image Parameter");
imageDepth = Integer.parseInt(referenceParams.get("ImageDepth"));
pixelSizeX = referenceParams.get("WidthConvertValue");
pixelSizeY = referenceParams.get("HeightConvertValue");
int index = 0;
IniTable laser = f.getTable("Laser " + index + " Parameters");
while (laser != null) {
laserEnabled = laser.get("Laser Enable").equals("1");
if (laserEnabled) {
wavelengths.add(new Integer(laser.get("LaserWavelength")));
}
creationDate = laser.get("ImageCaputreDate");
if (creationDate == null) {
creationDate = laser.get("ImageCaptureDate");
}
index++;
laser = f.getTable("Laser " + index + " Parameters");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
index = 1;
IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters");
while (guiChannel != null) {
ChannelData channel = new ChannelData();
channel.gain = new Double(guiChannel.get("AnalogPMTGain"));
channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage"));
channel.barrierFilter = guiChannel.get("BF Name");
channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0;
channel.name = guiChannel.get("CH Name");
channel.dyeName = guiChannel.get("DyeName");
channel.emissionFilter = guiChannel.get("EmissionDM Name");
channel.emWave = new Integer(guiChannel.get("EmissionWavelength"));
channel.excitationFilter = guiChannel.get("ExcitationDM Name");
channel.exWave = new Integer(guiChannel.get("ExcitationWavelength"));
channels.add(channel);
index++;
guiChannel = f.getTable("GUI Channel " + index + " Parameters");
}
index = 1;
IniTable channel = f.getTable("Channel " + index + " Parameters");
while (channel != null) {
String illumination = channel.get("LightType");
if (illumination == null) {
// Ignored
}
else if (illumination.indexOf("fluorescence") != -1) {
illumination = "Epifluorescence";
}
else if (illumination.indexOf("transmitted") != -1) {
illumination = "Transmitted";
}
else illumination = null;
illuminations.add(illumination);
index++;
channel = f.getTable("Channel " + index + " Parameters");
}
for (IniTable table : f) {
String tableName = table.get(IniTable.HEADER_KEY);
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta(tableName + " " + key, table.get(key));
}
}
}
LOGGER.info("Initializing helper readers");
// populate core metadata for preview series
if (previewNames.size() > 0) {
Vector<String> v = new Vector<String>();
for (int i=0; i<previewNames.size(); i++) {
String ss = previewNames.get(i);
ss = replaceExtension(ss, "pty", "tif");
if (ss.endsWith(".tif")) v.add(ss);
}
previewNames = v;
if (previewNames.size() > 0) {
core = new CoreMetadata[2];
core[0] = new CoreMetadata();
core[1] = new CoreMetadata();
IFDList ifds = null;
for (String previewName : previewNames) {
RandomAccessInputStream preview = getFile(previewName);
TiffParser tp = new TiffParser(preview);
ifds = tp.getIFDs();
preview.close();
core[1].imageCount += ifds.size();
}
core[1].sizeX = (int) ifds.get(0).getImageWidth();
core[1].sizeY = (int) ifds.get(0).getImageLength();
core[1].sizeZ = 1;
core[1].sizeT = 1;
core[1].sizeC = core[1].imageCount;
core[1].rgb = false;
int bits = ifds.get(0).getBitsPerSample()[0];
while ((bits % 8) != 0) bits++;
switch (bits) {
case 8:
core[1].pixelType = FormatTools.UINT8;
break;
case 16:
core[1].pixelType = FormatTools.UINT16;
break;
case 32:
core[1].pixelType = FormatTools.UINT32;
}
core[1].dimensionOrder = "XYCZT";
core[1].indexed = false;
}
}
core[0].imageCount = filenames.size();
tiffs = new Vector<String>(getImageCount());
thumbReader = new BMPReader();
thumbId = replaceExtension(thumbId, "pty", "bmp");
thumbId = sanitizeFile(thumbId, path);
LOGGER.info("Reading additional metadata");
// open each INI file (.pty extension) and build list of TIFF files
String tiffPath = null;
core[0].dimensionOrder = "XY";
for (int i=0, ii=0; ii<getImageCount(); i++, ii++) {
String file = filenames.get(new Integer(i));
while (file == null) file = filenames.get(new Integer(++i));
file = sanitizeFile(file, path);
if (file.indexOf(File.separator) != -1) {
tiffPath = file.substring(0, file.lastIndexOf(File.separator));
}
else tiffPath = file;
Location ptyFile = new Location(file);
if (!isOIB && !ptyFile.exists()) {
LOGGER.warn("Could not find .pty file ({}); guessing at the " +
"corresponding TIFF file.", file);
String tiff = replaceExtension(file, ".pty", ".tif");
tiffs.add(ii, tiff);
continue;
}
IniList pty = getIniFile(file);
IniTable fileInfo = pty.getTable("File Info");
file = sanitizeValue(fileInfo.get("DataName"));
if (!isPreviewName(file)) {
while (file.indexOf("GST") != -1) {
file = removeGST(file);
}
if (!mappedOIF) {
file = new Location(tiffPath, file).getAbsolutePath();
if (isOIB) {
file = file.substring(file.indexOf(File.separator));
}
}
tiffs.add(ii, file);
}
for (int dim=0; dim<NUM_DIMENSIONS; dim++) {
IniTable axis = pty.getTable("Axis " + dim + " Parameters");
if (axis == null) break;
boolean addAxis = Integer.parseInt(axis.get("Number")) > 1;
if (dim == 2) {
if (addAxis && getDimensionOrder().indexOf("C") == -1) {
core[0].dimensionOrder += "C";
}
}
else if (dim == 3) {
if (addAxis && getDimensionOrder().indexOf("Z") == -1) {
core[0].dimensionOrder += "Z";
}
}
else if (dim == 4) {
if (addAxis && getDimensionOrder().indexOf("T") == -1) {
core[0].dimensionOrder += "T";
}
}
}
IniTable acquisition = pty.getTable("Acquisition Parameters Common");
magnification = acquisition.get("Magnification");
lensNA = acquisition.get("ObjectiveLens NAValue");
objectiveName = acquisition.get("ObjectiveLens Name");
workingDistance = acquisition.get("ObjectiveLens WDValue");
pinholeSize = acquisition.get("PinholeDiameter");
String validBitCounts = acquisition.get("ValidBitCounts");
if (validBitCounts != null) {
core[0].bitsPerPixel = Integer.parseInt(validBitCounts);
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : pty) {
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta("Image " + ii + " : " + key, table.get(key));
}
}
}
}
if (tiffs.size() != getImageCount()) {
core[0].imageCount = tiffs.size();
}
usedFiles = new Vector<String>();
if (tiffPath != null) {
usedFiles.add(id);
if (!isOIB) {
Location dir = new Location(tiffPath);
if (!dir.exists()) {
throw new FormatException(
"Required directory " + tiffPath + " was not found.");
}
String[] list = mappedOIF ?
Location.getIdMap().keySet().toArray(new String[0]) : dir.list();
for (int i=0; i<list.length; i++) {
if (mappedOIF) usedFiles.add(list[i]);
else {
String p = new Location(tiffPath, list[i]).getAbsolutePath();
String check = p.toLowerCase();
if (!check.endsWith(".tif") && !check.endsWith(".pty") &&
!check.endsWith(".roi") && !check.endsWith(".lut") &&
!check.endsWith(".bmp"))
{
continue;
}
usedFiles.add(p);
}
}
}
}
LOGGER.info("Populating metadata");
// calculate axis sizes
int realChannels = 0;
for (int i=0; i<NUM_DIMENSIONS; i++) {
int ss = Integer.parseInt(size[i]);
if (pixelSize[i] == null) pixelSize[i] = 1.0;
if (code[i].equals("X")) core[0].sizeX = ss;
else if (code[i].equals("Y")) core[0].sizeY = ss;
else if (code[i].equals("Z")) {
core[0].sizeZ = ss;
// Z size stored in nm
pixelSizeZ =
Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000);
}
else if (code[i].equals("T")) {
core[0].sizeT = ss;
pixelSizeT =
Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000);
}
else if (ss > 0) {
if (getSizeC() == 0) core[0].sizeC = ss;
else core[0].sizeC *= ss;
if (code[i].equals("C")) realChannels = ss;
}
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
if (getImageCount() == getSizeC() && getSizeY() == 1) {
core[0].imageCount *= getSizeZ() * getSizeT();
}
else if (getImageCount() == getSizeC()) {
core[0].sizeZ = 1;
core[0].sizeT = 1;
}
if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) {
int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount();
if (diff == previewNames.size() || diff < 0) {
diff /= getSizeC();
if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff;
else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff;
}
else core[0].imageCount += diff;
}
if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T";
switch (imageDepth) {
case 1:
core[0].pixelType = FormatTools.UINT8;
break;
case 2:
core[0].pixelType = FormatTools.UINT16;
break;
case 4:
core[0].pixelType = FormatTools.UINT32;
break;
default:
throw new RuntimeException("Unsupported pixel depth: " + imageDepth);
}
// set up thumbnail file mapping
try {
RandomAccessInputStream thumb = getFile(thumbId);
byte[] b = new byte[(int) thumb.length()];
thumb.read(b);
thumb.close();
Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b));
thumbReader.setId("thumbnail.bmp");
for (int i=0; i<getSeriesCount(); i++) {
core[i].thumbSizeX = thumbReader.getSizeX();
core[i].thumbSizeY = thumbReader.getSizeY();
}
Location.mapFile("thumbnail.bmp", null);
}
catch (IOException e) {
LOGGER.debug("Could not read thumbnail", e);
}
// initialize lookup table
lut = new short[getSizeC()][3][65536];
byte[] buffer = new byte[65536 * 4];
int count = (int) Math.min(getSizeC(), lutNames.size());
for (int c=0; c<count; c++) {
try {
RandomAccessInputStream stream = getFile(lutNames.get(c));
stream.seek(stream.length() - 65536 * 4);
stream.read(buffer);
stream.close();
for (int q=0; q<buffer.length; q+=4) {
lut[c][0][q / 4] = buffer[q + 1];
lut[c][1][q / 4] = buffer[q + 2];
lut[c][2][q / 4] = buffer[q + 3];
}
}
catch (IOException e) {
LOGGER.debug("Could not read LUT", e);
lut = null;
break;
}
}
for (int i=0; i<getSeriesCount(); i++) {
core[i].rgb = false;
core[i].littleEndian = true;
core[i].interleaved = false;
core[i].metadataComplete = true;
core[i].indexed = false;
core[i].falseColor = false;
}
// populate MetadataStore
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
if (creationDate != null) {
creationDate = creationDate.replaceAll("'", "");
creationDate = DateTools.formatDate(creationDate, DATE_FORMAT);
}
for (int i=0; i<getSeriesCount(); i++) {
// populate Image data
store.setImageName("Series " + (i + 1), i);
if (creationDate != null) store.setImageCreationDate(creationDate, i);
else MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
populateMetadataStore(store, path);
}
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
isOIB = checkSuffix(id, OIB_SUFFIX);
if (isOIB) {
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(id));
}
// mappedOIF is used to distinguish between datasets that are being read
// directly (e.g. using ImageJ or showinf), and datasets that are being
// imported through omebf. In the latter case, the necessary directory
// structure is not preserved (only relative file names are stored in
// OMEIS), so we will need to use slightly different logic to build the
// list of associated files.
boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists();
wavelengths = new Vector<Integer>();
illuminations = new Vector<String>();
channels = new Vector<ChannelData>();
String oifName = null;
if (isOIB) {
oifName = mapOIBFiles();
}
else {
// make sure we have the OIF file, not a TIFF
if (!checkSuffix(id, OIF_SUFFIX)) {
currentId = findOIFFile(id);
initFile(currentId);
}
oifName = currentId;
}
String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath();
String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" :
oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1);
try {
getFile(oifName);
}
catch (IOException e) {
oifName = oifName.replaceAll(".oif", ".OIF");
}
// parse key/value pairs from the OIF file
code = new String[NUM_DIMENSIONS];
size = new String[NUM_DIMENSIONS];
pixelSize = new Double[NUM_DIMENSIONS];
previewNames = new Vector<String>();
boolean laserEnabled = true;
IniList f = getIniFile(oifName);
IniTable saveInfo = f.getTable("ProfileSaveInfo");
String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]);
for (String key : saveKeys) {
String value = saveInfo.get(key).toString();
value = sanitizeValue(value).trim();
if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
filenames.put(new Integer(key.substring(11)), value);
}
else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 &&
!isPreviewName(value))
{
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1).trim();
}
try {
roiFilenames.put(new Integer(key.substring(11)), value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("PtyFileNameS")) ptyStart = value;
else if (key.equals("PtyFileNameE")) ptyEnd = value;
else if (key.equals("PtyFileNameT2")) ptyPattern = value;
else if (key.indexOf("Thumb") != -1) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
if (thumbId == null) thumbId = value.trim();
}
else if (key.startsWith("LutFileName")) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
lutNames.add(path + value);
}
else if (isPreviewName(value)) {
if (mappedOIF) {
value = value.substring(value.lastIndexOf(File.separator) + 1);
}
previewNames.add(path + value.trim());
}
}
for (int i=0; i<NUM_DIMENSIONS; i++) {
IniTable commonParams = f.getTable("Axis " + i + " Parameters Common");
code[i] = commonParams.get("AxisCode");
size[i] = commonParams.get("MaxSize");
double end = Double.parseDouble(commonParams.get("EndPosition"));
double start = Double.parseDouble(commonParams.get("StartPosition"));
pixelSize[i] = end - start;
}
IniTable referenceParams = f.getTable("Reference Image Parameter");
imageDepth = Integer.parseInt(referenceParams.get("ImageDepth"));
pixelSizeX = referenceParams.get("WidthConvertValue");
pixelSizeY = referenceParams.get("HeightConvertValue");
int index = 0;
IniTable laser = f.getTable("Laser " + index + " Parameters");
while (laser != null) {
laserEnabled = laser.get("Laser Enable").equals("1");
if (laserEnabled) {
wavelengths.add(new Integer(laser.get("LaserWavelength")));
}
creationDate = laser.get("ImageCaputreDate");
if (creationDate == null) {
creationDate = laser.get("ImageCaptureDate");
}
index++;
laser = f.getTable("Laser " + index + " Parameters");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
index = 1;
IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters");
while (guiChannel != null) {
ChannelData channel = new ChannelData();
channel.gain = new Double(guiChannel.get("AnalogPMTGain"));
channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage"));
channel.barrierFilter = guiChannel.get("BF Name");
channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0;
channel.name = guiChannel.get("CH Name");
channel.dyeName = guiChannel.get("DyeName");
channel.emissionFilter = guiChannel.get("EmissionDM Name");
channel.emWave = new Integer(guiChannel.get("EmissionWavelength"));
channel.excitationFilter = guiChannel.get("ExcitationDM Name");
channel.exWave = new Integer(guiChannel.get("ExcitationWavelength"));
channels.add(channel);
index++;
guiChannel = f.getTable("GUI Channel " + index + " Parameters");
}
index = 1;
IniTable channel = f.getTable("Channel " + index + " Parameters");
while (channel != null) {
String illumination = channel.get("LightType");
if (illumination == null) {
// Ignored
}
else if (illumination.indexOf("fluorescence") != -1) {
illumination = "Epifluorescence";
}
else if (illumination.indexOf("transmitted") != -1) {
illumination = "Transmitted";
}
else illumination = null;
illuminations.add(illumination);
index++;
channel = f.getTable("Channel " + index + " Parameters");
}
for (IniTable table : f) {
String tableName = table.get(IniTable.HEADER_KEY);
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta(tableName + " " + key, table.get(key));
}
}
}
LOGGER.info("Initializing helper readers");
// populate core metadata for preview series
if (previewNames.size() > 0) {
Vector<String> v = new Vector<String>();
for (int i=0; i<previewNames.size(); i++) {
String ss = previewNames.get(i);
ss = replaceExtension(ss, "pty", "tif");
if (ss.endsWith(".tif")) v.add(ss);
}
previewNames = v;
if (previewNames.size() > 0) {
core = new CoreMetadata[2];
core[0] = new CoreMetadata();
core[1] = new CoreMetadata();
IFDList ifds = null;
for (String previewName : previewNames) {
RandomAccessInputStream preview = getFile(previewName);
TiffParser tp = new TiffParser(preview);
ifds = tp.getIFDs();
preview.close();
core[1].imageCount += ifds.size();
}
core[1].sizeX = (int) ifds.get(0).getImageWidth();
core[1].sizeY = (int) ifds.get(0).getImageLength();
core[1].sizeZ = 1;
core[1].sizeT = 1;
core[1].sizeC = core[1].imageCount;
core[1].rgb = false;
int bits = ifds.get(0).getBitsPerSample()[0];
while ((bits % 8) != 0) bits++;
switch (bits) {
case 8:
core[1].pixelType = FormatTools.UINT8;
break;
case 16:
core[1].pixelType = FormatTools.UINT16;
break;
case 32:
core[1].pixelType = FormatTools.UINT32;
}
core[1].dimensionOrder = "XYCZT";
core[1].indexed = false;
}
}
core[0].imageCount = filenames.size();
tiffs = new Vector<String>(getImageCount());
thumbReader = new BMPReader();
thumbId = replaceExtension(thumbId, "pty", "bmp");
thumbId = sanitizeFile(thumbId, path);
LOGGER.info("Reading additional metadata");
// open each INI file (.pty extension) and build list of TIFF files
String tiffPath = null;
core[0].dimensionOrder = "XY";
for (int i=0, ii=0; ii<getImageCount(); i++, ii++) {
String file = filenames.get(new Integer(i));
while (file == null) file = filenames.get(new Integer(++i));
file = sanitizeFile(file, path);
if (file.indexOf(File.separator) != -1) {
tiffPath = file.substring(0, file.lastIndexOf(File.separator));
}
else tiffPath = file;
Location ptyFile = new Location(file);
if (!isOIB && !ptyFile.exists()) {
LOGGER.warn("Could not find .pty file ({}); guessing at the " +
"corresponding TIFF file.", file);
String tiff = replaceExtension(file, ".pty", ".tif");
tiffs.add(ii, tiff);
continue;
}
IniList pty = getIniFile(file);
IniTable fileInfo = pty.getTable("File Info");
file = sanitizeValue(fileInfo.get("DataName"));
if (!isPreviewName(file)) {
while (file.indexOf("GST") != -1) {
file = removeGST(file);
}
if (!mappedOIF) {
file = new Location(tiffPath, file).getAbsolutePath();
if (isOIB) {
file = file.substring(file.indexOf(File.separator));
}
}
tiffs.add(ii, file);
}
for (int dim=0; dim<NUM_DIMENSIONS; dim++) {
IniTable axis = pty.getTable("Axis " + dim + " Parameters");
if (axis == null) break;
boolean addAxis = Integer.parseInt(axis.get("Number")) > 1;
if (dim == 2) {
if (addAxis && getDimensionOrder().indexOf("C") == -1) {
core[0].dimensionOrder += "C";
}
}
else if (dim == 3) {
if (addAxis && getDimensionOrder().indexOf("Z") == -1) {
core[0].dimensionOrder += "Z";
}
}
else if (dim == 4) {
if (addAxis && getDimensionOrder().indexOf("T") == -1) {
core[0].dimensionOrder += "T";
}
}
}
IniTable acquisition = pty.getTable("Acquisition Parameters Common");
if (acquisition != null) {
magnification = acquisition.get("Magnification");
lensNA = acquisition.get("ObjectiveLens NAValue");
objectiveName = acquisition.get("ObjectiveLens Name");
workingDistance = acquisition.get("ObjectiveLens WDValue");
pinholeSize = acquisition.get("PinholeDiameter");
String validBitCounts = acquisition.get("ValidBitCounts");
if (validBitCounts != null) {
core[0].bitsPerPixel = Integer.parseInt(validBitCounts);
}
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
for (IniTable table : pty) {
String[] keys = table.keySet().toArray(new String[table.size()]);
for (String key : keys) {
addGlobalMeta("Image " + ii + " : " + key, table.get(key));
}
}
}
}
if (tiffs.size() != getImageCount()) {
core[0].imageCount = tiffs.size();
}
usedFiles = new Vector<String>();
if (tiffPath != null) {
usedFiles.add(id);
if (!isOIB) {
Location dir = new Location(tiffPath);
if (!dir.exists()) {
throw new FormatException(
"Required directory " + tiffPath + " was not found.");
}
String[] list = mappedOIF ?
Location.getIdMap().keySet().toArray(new String[0]) : dir.list();
for (int i=0; i<list.length; i++) {
if (mappedOIF) usedFiles.add(list[i]);
else {
String p = new Location(tiffPath, list[i]).getAbsolutePath();
String check = p.toLowerCase();
if (!check.endsWith(".tif") && !check.endsWith(".pty") &&
!check.endsWith(".roi") && !check.endsWith(".lut") &&
!check.endsWith(".bmp"))
{
continue;
}
usedFiles.add(p);
}
}
}
}
LOGGER.info("Populating metadata");
// calculate axis sizes
int realChannels = 0;
for (int i=0; i<NUM_DIMENSIONS; i++) {
int ss = Integer.parseInt(size[i]);
if (pixelSize[i] == null) pixelSize[i] = 1.0;
if (code[i].equals("X")) core[0].sizeX = ss;
else if (code[i].equals("Y")) core[0].sizeY = ss;
else if (code[i].equals("Z")) {
core[0].sizeZ = ss;
// Z size stored in nm
pixelSizeZ =
Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000);
}
else if (code[i].equals("T")) {
core[0].sizeT = ss;
pixelSizeT =
Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000);
}
else if (ss > 0) {
if (getSizeC() == 0) core[0].sizeC = ss;
else core[0].sizeC *= ss;
if (code[i].equals("C")) realChannels = ss;
}
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
if (getImageCount() == getSizeC() && getSizeY() == 1) {
core[0].imageCount *= getSizeZ() * getSizeT();
}
else if (getImageCount() == getSizeC()) {
core[0].sizeZ = 1;
core[0].sizeT = 1;
}
if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) {
int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount();
if (diff == previewNames.size() || diff < 0) {
diff /= getSizeC();
if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff;
else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff;
}
else core[0].imageCount += diff;
}
if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T";
switch (imageDepth) {
case 1:
core[0].pixelType = FormatTools.UINT8;
break;
case 2:
core[0].pixelType = FormatTools.UINT16;
break;
case 4:
core[0].pixelType = FormatTools.UINT32;
break;
default:
throw new RuntimeException("Unsupported pixel depth: " + imageDepth);
}
// set up thumbnail file mapping
try {
RandomAccessInputStream thumb = getFile(thumbId);
byte[] b = new byte[(int) thumb.length()];
thumb.read(b);
thumb.close();
Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b));
thumbReader.setId("thumbnail.bmp");
for (int i=0; i<getSeriesCount(); i++) {
core[i].thumbSizeX = thumbReader.getSizeX();
core[i].thumbSizeY = thumbReader.getSizeY();
}
Location.mapFile("thumbnail.bmp", null);
}
catch (IOException e) {
LOGGER.debug("Could not read thumbnail", e);
}
// initialize lookup table
lut = new short[getSizeC()][3][65536];
byte[] buffer = new byte[65536 * 4];
int count = (int) Math.min(getSizeC(), lutNames.size());
for (int c=0; c<count; c++) {
try {
RandomAccessInputStream stream = getFile(lutNames.get(c));
stream.seek(stream.length() - 65536 * 4);
stream.read(buffer);
stream.close();
for (int q=0; q<buffer.length; q+=4) {
lut[c][0][q / 4] = buffer[q + 1];
lut[c][1][q / 4] = buffer[q + 2];
lut[c][2][q / 4] = buffer[q + 3];
}
}
catch (IOException e) {
LOGGER.debug("Could not read LUT", e);
lut = null;
break;
}
}
for (int i=0; i<getSeriesCount(); i++) {
core[i].rgb = false;
core[i].littleEndian = true;
core[i].interleaved = false;
core[i].metadataComplete = true;
core[i].indexed = false;
core[i].falseColor = false;
}
// populate MetadataStore
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this);
if (creationDate != null) {
creationDate = creationDate.replaceAll("'", "");
creationDate = DateTools.formatDate(creationDate, DATE_FORMAT);
}
for (int i=0; i<getSeriesCount(); i++) {
// populate Image data
store.setImageName("Series " + (i + 1), i);
if (creationDate != null) store.setImageCreationDate(creationDate, i);
else MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
populateMetadataStore(store, path);
}
}
|
diff --git a/src/java/org/apache/cassandra/dht/AbstractBounds.java b/src/java/org/apache/cassandra/dht/AbstractBounds.java
index d1eedcbd6..becce444d 100644
--- a/src/java/org/apache/cassandra/dht/AbstractBounds.java
+++ b/src/java/org/apache/cassandra/dht/AbstractBounds.java
@@ -1,137 +1,137 @@
package org.apache.cassandra.dht;
/*
*
* 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.
*
*/
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import org.apache.cassandra.io.ICompactSerializer2;
import org.apache.cassandra.utils.Pair;
public abstract class AbstractBounds implements Serializable
{
private static final long serialVersionUID = 1L;
private static AbstractBoundsSerializer serializer = new AbstractBoundsSerializer();
public static ICompactSerializer2<AbstractBounds> serializer()
{
return serializer;
}
private enum Type
{
RANGE,
BOUNDS
}
public final Token left;
public final Token right;
protected transient final IPartitioner partitioner;
public AbstractBounds(Token left, Token right, IPartitioner partitioner)
{
this.left = left;
this.right = right;
this.partitioner = partitioner;
}
/**
* Given token T and AbstractBounds ?L,R], returns Pair(?L,T], ?T,R])
* (where ? means that the same type of Bounds is returned -- Range or Bounds -- as the original.)
* The original AbstractBounds must contain the token T.
* If the split would cause one of the left or right side to be empty, it will be null in the result pair.
*/
public Pair<AbstractBounds,AbstractBounds> split(Token token)
{
assert left.equals(token) || contains(token);
AbstractBounds lb = createFrom(token);
// we contain this token, so only one of the left or right can be empty
AbstractBounds rb = lb != null && token.equals(right) ? null : new Range(token, right);
return new Pair<AbstractBounds,AbstractBounds>(lb, rb);
}
@Override
public int hashCode()
{
return 31 * left.hashCode() + right.hashCode();
}
public abstract boolean equals(Object obj);
public abstract boolean contains(Token start);
/** @return A clone of this AbstractBounds with a new right Token, or null if an identical range would be created. */
public abstract AbstractBounds createFrom(Token right);
public abstract List<AbstractBounds> unwrap();
/**
* @return A copy of the given list of non-intersecting bounds with all bounds unwrapped, sorted by bound.left.
* This method does not allow overlapping ranges as input.
*/
public static List<AbstractBounds> normalize(Collection<? extends AbstractBounds> bounds)
{
// unwrap all
List<AbstractBounds> output = new ArrayList<AbstractBounds>();
AbstractBounds previous = null;
for (AbstractBounds bound : bounds)
{
List<AbstractBounds> unwrapped = bound.unwrap();
assert previous == null || previous.right.compareTo(unwrapped.get(0).left) <= 0 :
- "Overlapping ranges passed to normalize: see CASSANDRA-2461: " + previous + " and " + unwrapped;
+ "Overlapping ranges passed to normalize: see CASSANDRA-2641: " + previous + " and " + unwrapped;
output.addAll(unwrapped);
previous = unwrapped.get(unwrapped.size() - 1);
}
// sort by left
Collections.sort(output, new Comparator<AbstractBounds>()
{
public int compare(AbstractBounds b1, AbstractBounds b2)
{
return b1.left.compareTo(b2.left);
}
});
return output;
}
private static class AbstractBoundsSerializer implements ICompactSerializer2<AbstractBounds>
{
public void serialize(AbstractBounds range, DataOutput out) throws IOException
{
out.writeInt(range instanceof Range ? Type.RANGE.ordinal() : Type.BOUNDS.ordinal());
Token.serializer().serialize(range.left, out);
Token.serializer().serialize(range.right, out);
}
public AbstractBounds deserialize(DataInput in) throws IOException
{
if (in.readInt() == Type.RANGE.ordinal())
return new Range(Token.serializer().deserialize(in), Token.serializer().deserialize(in));
return new Bounds(Token.serializer().deserialize(in), Token.serializer().deserialize(in));
}
}
}
| true | true | public static List<AbstractBounds> normalize(Collection<? extends AbstractBounds> bounds)
{
// unwrap all
List<AbstractBounds> output = new ArrayList<AbstractBounds>();
AbstractBounds previous = null;
for (AbstractBounds bound : bounds)
{
List<AbstractBounds> unwrapped = bound.unwrap();
assert previous == null || previous.right.compareTo(unwrapped.get(0).left) <= 0 :
"Overlapping ranges passed to normalize: see CASSANDRA-2461: " + previous + " and " + unwrapped;
output.addAll(unwrapped);
previous = unwrapped.get(unwrapped.size() - 1);
}
// sort by left
Collections.sort(output, new Comparator<AbstractBounds>()
{
public int compare(AbstractBounds b1, AbstractBounds b2)
{
return b1.left.compareTo(b2.left);
}
});
return output;
}
| public static List<AbstractBounds> normalize(Collection<? extends AbstractBounds> bounds)
{
// unwrap all
List<AbstractBounds> output = new ArrayList<AbstractBounds>();
AbstractBounds previous = null;
for (AbstractBounds bound : bounds)
{
List<AbstractBounds> unwrapped = bound.unwrap();
assert previous == null || previous.right.compareTo(unwrapped.get(0).left) <= 0 :
"Overlapping ranges passed to normalize: see CASSANDRA-2641: " + previous + " and " + unwrapped;
output.addAll(unwrapped);
previous = unwrapped.get(unwrapped.size() - 1);
}
// sort by left
Collections.sort(output, new Comparator<AbstractBounds>()
{
public int compare(AbstractBounds b1, AbstractBounds b2)
{
return b1.left.compareTo(b2.left);
}
});
return output;
}
|
diff --git a/pixi/src/main/java/org/openpixi/pixi/physics/fields/PoissonSolver.java b/pixi/src/main/java/org/openpixi/pixi/physics/fields/PoissonSolver.java
index a0a60ed8..ebd48dad 100644
--- a/pixi/src/main/java/org/openpixi/pixi/physics/fields/PoissonSolver.java
+++ b/pixi/src/main/java/org/openpixi/pixi/physics/fields/PoissonSolver.java
@@ -1,72 +1,72 @@
package org.openpixi.pixi.physics.fields;
import edu.emory.mathcs.jtransforms.fft.*;
import org.openpixi.pixi.physics.grid.Grid;
import java.math.*;
public class PoissonSolver {
public PoissonSolver() {
}
public static void solve2D(Grid g) {
int rows = g.rho.length;
int columns = 2 * g.rho[0].length;
int n = 0;
double[][] trho = new double[rows][columns];
double[][] phi = new double[rows][columns];
DoubleFFT_2D fft = new DoubleFFT_2D(rows, columns/2);
//prepare input for fft
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
trho[i][j] = g.rho[i][j-n];
trho[i][j+1] = 0;
n += 1;
}
}
//perform Fourier transformation
fft.complexForward(trho);
//solve Poisson equation in Fourier space
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j += 2) {
- double d = (4 - 2 * Math.cos(2 * Math.PI * i / g.numCellsX) - 2 * Math.cos(2 * Math.PI * j / g.numCellsY));
+ double d = (4 - 2 * Math.cos((2 * Math.PI * i) / g.numCellsX) - 2 * Math.cos((2 * Math.PI * (j/2)) / g.numCellsY));
if (d != 0) {
phi[i][j] = (g.cellWidth * g.cellHeight * trho[i][j]) / d; ;
// phi[i][j+1] = (g.cellWidth * g.cellHeight * trho[i][j+1]) / d;
} else {
- phi[i][j] = 0;
- phi[i][j+1] = 0;
+ phi[i][j] = trho[i][j];
+ phi[i][j+1] = trho[i][j+1];
}
// System.out.println(trho[i][j] + " " + trho[i][j+1]);
}
}
//perform inverse Fourier transform
fft.complexInverse(phi, true);
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
System.out.println(phi[i][j] + " " + phi[i][j+1]);
}
}
//prepare output
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
g.phi[i][j-n] = phi[i][j];
n += 1;
}
}
}
}
| false | true | public static void solve2D(Grid g) {
int rows = g.rho.length;
int columns = 2 * g.rho[0].length;
int n = 0;
double[][] trho = new double[rows][columns];
double[][] phi = new double[rows][columns];
DoubleFFT_2D fft = new DoubleFFT_2D(rows, columns/2);
//prepare input for fft
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
trho[i][j] = g.rho[i][j-n];
trho[i][j+1] = 0;
n += 1;
}
}
//perform Fourier transformation
fft.complexForward(trho);
//solve Poisson equation in Fourier space
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j += 2) {
double d = (4 - 2 * Math.cos(2 * Math.PI * i / g.numCellsX) - 2 * Math.cos(2 * Math.PI * j / g.numCellsY));
if (d != 0) {
phi[i][j] = (g.cellWidth * g.cellHeight * trho[i][j]) / d; ;
// phi[i][j+1] = (g.cellWidth * g.cellHeight * trho[i][j+1]) / d;
} else {
phi[i][j] = 0;
phi[i][j+1] = 0;
}
// System.out.println(trho[i][j] + " " + trho[i][j+1]);
}
}
//perform inverse Fourier transform
fft.complexInverse(phi, true);
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
System.out.println(phi[i][j] + " " + phi[i][j+1]);
}
}
//prepare output
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
g.phi[i][j-n] = phi[i][j];
n += 1;
}
}
}
| public static void solve2D(Grid g) {
int rows = g.rho.length;
int columns = 2 * g.rho[0].length;
int n = 0;
double[][] trho = new double[rows][columns];
double[][] phi = new double[rows][columns];
DoubleFFT_2D fft = new DoubleFFT_2D(rows, columns/2);
//prepare input for fft
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
trho[i][j] = g.rho[i][j-n];
trho[i][j+1] = 0;
n += 1;
}
}
//perform Fourier transformation
fft.complexForward(trho);
//solve Poisson equation in Fourier space
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j += 2) {
double d = (4 - 2 * Math.cos((2 * Math.PI * i) / g.numCellsX) - 2 * Math.cos((2 * Math.PI * (j/2)) / g.numCellsY));
if (d != 0) {
phi[i][j] = (g.cellWidth * g.cellHeight * trho[i][j]) / d; ;
// phi[i][j+1] = (g.cellWidth * g.cellHeight * trho[i][j+1]) / d;
} else {
phi[i][j] = trho[i][j];
phi[i][j+1] = trho[i][j+1];
}
// System.out.println(trho[i][j] + " " + trho[i][j+1]);
}
}
//perform inverse Fourier transform
fft.complexInverse(phi, true);
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
System.out.println(phi[i][j] + " " + phi[i][j+1]);
}
}
//prepare output
for(int i = 0; i < rows; i++) {
n = 0;
for(int j = 0; j < columns; j += 2) {
g.phi[i][j-n] = phi[i][j];
n += 1;
}
}
}
|
diff --git a/java/src/org/broadinstitute/sting/gatk/executive/LinearMicroScheduler.java b/java/src/org/broadinstitute/sting/gatk/executive/LinearMicroScheduler.java
index 44db167e7..d9aa0e850 100644
--- a/java/src/org/broadinstitute/sting/gatk/executive/LinearMicroScheduler.java
+++ b/java/src/org/broadinstitute/sting/gatk/executive/LinearMicroScheduler.java
@@ -1,84 +1,85 @@
package org.broadinstitute.sting.gatk.executive;
import org.broadinstitute.sting.gatk.datasources.providers.ShardDataProvider;
import org.broadinstitute.sting.gatk.datasources.shards.Shard;
import org.broadinstitute.sting.gatk.datasources.shards.ShardStrategy;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.ReferenceOrderedDataSource;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.SAMDataSource;
import org.broadinstitute.sting.gatk.walkers.Walker;
import org.broadinstitute.sting.gatk.io.DirectOutputTracker;
import org.broadinstitute.sting.gatk.io.OutputTracker;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.utils.fasta.IndexedFastaSequenceFile;
import java.util.Collection;
/** A micro-scheduling manager for single-threaded execution of a traversal. */
public class LinearMicroScheduler extends MicroScheduler {
/**
* A direct output tracker for directly managing output.
*/
private DirectOutputTracker outputTracker = new DirectOutputTracker();
/**
* Create a new linear microscheduler to process the given reads and reference.
*
* @param walker Walker for the traversal.
* @param reads Reads file(s) to process.
* @param reference Reference for driving the traversal.
* @param rods Reference-ordered data.
*/
protected LinearMicroScheduler(GenomeAnalysisEngine engine, Walker walker, SAMDataSource reads, IndexedFastaSequenceFile reference, Collection<ReferenceOrderedDataSource> rods ) {
super(engine, walker, reads, reference, rods);
}
/**
* Run this traversal over the specified subsection of the dataset.
*
* @param walker Computation to perform over dataset.
* @param shardStrategy A strategy for sharding the data.
*/
public Object execute(Walker walker, ShardStrategy shardStrategy, int maxIterations) {
// Having maxiterations in the execute method is a holdover from the old TraversalEngine days.
// Lets do something else with this.
traversalEngine.setMaximumIterations(maxIterations);
walker.initialize();
Accumulator accumulator = Accumulator.create(engine,walker);
for (Shard shard : shardStrategy) {
// New experimental code for managing locus intervals.
// TODO: we'll need a similar but slightly different strategy for dealing with read intervals, so generalize this code.
- if(shard.getShardType() == Shard.ShardType.LOCUS || shard.getShardType() == Shard.ShardType.LOCUS_INTERVAL) {
+ if((shard.getShardType() == Shard.ShardType.LOCUS || shard.getShardType() == Shard.ShardType.LOCUS_INTERVAL) &&
+ shard.getGenomeLocs().size() > 0) {
WindowMaker windowMaker = new WindowMaker(getReadIterator(shard),shard.getGenomeLocs());
for(WindowMaker.WindowMakerIterator iterator: windowMaker) {
ShardDataProvider dataProvider = new ShardDataProvider(shard,iterator.getLocus(),iterator,reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
windowMaker.close();
}
else {
ShardDataProvider dataProvider = new ShardDataProvider(shard,null,getReadIterator(shard),reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
}
Object result = accumulator.finishTraversal();
printOnTraversalDone(result);
outputTracker.close();
return accumulator;
}
/**
* @{inheritDoc}
*/
public OutputTracker getOutputTracker() { return outputTracker; }
}
| true | true | public Object execute(Walker walker, ShardStrategy shardStrategy, int maxIterations) {
// Having maxiterations in the execute method is a holdover from the old TraversalEngine days.
// Lets do something else with this.
traversalEngine.setMaximumIterations(maxIterations);
walker.initialize();
Accumulator accumulator = Accumulator.create(engine,walker);
for (Shard shard : shardStrategy) {
// New experimental code for managing locus intervals.
// TODO: we'll need a similar but slightly different strategy for dealing with read intervals, so generalize this code.
if(shard.getShardType() == Shard.ShardType.LOCUS || shard.getShardType() == Shard.ShardType.LOCUS_INTERVAL) {
WindowMaker windowMaker = new WindowMaker(getReadIterator(shard),shard.getGenomeLocs());
for(WindowMaker.WindowMakerIterator iterator: windowMaker) {
ShardDataProvider dataProvider = new ShardDataProvider(shard,iterator.getLocus(),iterator,reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
windowMaker.close();
}
else {
ShardDataProvider dataProvider = new ShardDataProvider(shard,null,getReadIterator(shard),reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
}
Object result = accumulator.finishTraversal();
printOnTraversalDone(result);
outputTracker.close();
return accumulator;
}
| public Object execute(Walker walker, ShardStrategy shardStrategy, int maxIterations) {
// Having maxiterations in the execute method is a holdover from the old TraversalEngine days.
// Lets do something else with this.
traversalEngine.setMaximumIterations(maxIterations);
walker.initialize();
Accumulator accumulator = Accumulator.create(engine,walker);
for (Shard shard : shardStrategy) {
// New experimental code for managing locus intervals.
// TODO: we'll need a similar but slightly different strategy for dealing with read intervals, so generalize this code.
if((shard.getShardType() == Shard.ShardType.LOCUS || shard.getShardType() == Shard.ShardType.LOCUS_INTERVAL) &&
shard.getGenomeLocs().size() > 0) {
WindowMaker windowMaker = new WindowMaker(getReadIterator(shard),shard.getGenomeLocs());
for(WindowMaker.WindowMakerIterator iterator: windowMaker) {
ShardDataProvider dataProvider = new ShardDataProvider(shard,iterator.getLocus(),iterator,reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
windowMaker.close();
}
else {
ShardDataProvider dataProvider = new ShardDataProvider(shard,null,getReadIterator(shard),reference,rods);
Object result = traversalEngine.traverse(walker, dataProvider, accumulator.getReduceInit());
accumulator.accumulate(dataProvider,result);
dataProvider.close();
}
}
Object result = accumulator.finishTraversal();
printOnTraversalDone(result);
outputTracker.close();
return accumulator;
}
|
diff --git a/src/com/androzic/track/TrackingService.java b/src/com/androzic/track/TrackingService.java
index 2e54039..7883d44 100644
--- a/src/com/androzic/track/TrackingService.java
+++ b/src/com/androzic/track/TrackingService.java
@@ -1,577 +1,579 @@
/*
* Androzic - android navigation client that uses OziExplorer maps (ozf2, ozfx3).
* Copyright (C) 2010-2012 Andrey Novikov <http://andreynovikov.info/>
*
* This file is part of Androzic application.
*
* Androzic 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.
* Androzic 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 Androzic. If not, see <http://www.gnu.org/licenses/>.
*/
package com.androzic.track;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import com.androzic.Androzic;
import com.androzic.MapActivity;
import com.androzic.R;
import com.androzic.location.ILocationListener;
import com.androzic.location.ILocationService;
import com.androzic.location.LocationService;
import com.androzic.util.OziExplorerFiles;
import com.androzic.util.TDateTime;
public class TrackingService extends Service implements OnSharedPreferenceChangeListener
{
private static final String TAG = "Tracking";
private static final int NOTIFICATION_ID = 24162;
public static final String ENABLE_TRACK = "enableTrack";
public static final String DISABLE_TRACK = "disableTrack";
public static final String BROADCAST_TRACKING_STATUS = "com.androzic.trackingStatusChanged";
private final RemoteCallbackList<ITrackingCallback> remoteCallbacks = new RemoteCallbackList<ITrackingCallback>();
private final Set<ITrackingListener> callbacks = new HashSet<ITrackingListener>();
private final static DecimalFormat coordFormat = new DecimalFormat("* ###0.000000", new DecimalFormatSymbols(Locale.ENGLISH));
private ILocationService locationService = null;
private final Binder binder = new LocalBinder();
private BufferedWriter trackWriter = null;
private boolean needsHeader = false;
private boolean errorState = false;
private boolean trackingEnabled = false;
private boolean isSuspended = false;
private Notification notification;
private PendingIntent contentIntent;
private Location lastWritenLocation = null;
private Location lastLocation = null;
private double distanceFromLastWriting = 0;
private long timeFromLastWriting = 0;
private boolean isContinous;
private long minTime = 2000; // 2 seconds (default)
private long maxTime = 300000; // 5 minutes
private int minDistance = 3; // 3 meters (default)
private int color = Color.RED;
private int fileInterval;
@Override
public void onCreate()
{
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_tracking_currentcolor));
onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_tracking_mintime));
onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_tracking_mindistance));
onSharedPreferenceChanged(sharedPreferences, getString(R.string.pref_tracking_currentinterval));
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
notification = new Notification();
contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, new Intent(this, MapActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK), 0);
registerReceiver(broadcastReceiver, new IntentFilter(LocationService.BROADCAST_LOCATING_STATUS));
Log.i(TAG, "Service started");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent != null && intent.getAction() != null)
{
if (intent.getAction().equals(ENABLE_TRACK) && ! trackingEnabled && ! isSuspended)
{
prepareNormalNotification();
trackingEnabled = true;
isSuspended = true;
isContinous = false;
connect();
}
if (intent.getAction().equals(DISABLE_TRACK) && trackingEnabled)
{
trackingEnabled = false;
isSuspended = false;
stopForeground(true);
disconnect();
closeFile();
sendBroadcast(new Intent(BROADCAST_TRACKING_STATUS));
}
}
return START_REDELIVER_INTENT | START_STICKY;
}
private void closeFile()
{
if (trackWriter != null)
{
try
{
trackWriter.close();
}
catch (Exception e)
{
Log.e(TAG, "Ex", e);
showErrorNotification();
}
trackWriter = null;
}
}
private void createFile(long time)
{
closeFile();
try
{
Androzic application = Androzic.getApplication();
+ if (application.trackPath == null)
+ return;
File dir = new File(application.trackPath);
if (! dir.exists())
dir.mkdirs();
String addon = "";
SimpleDateFormat formatter = new SimpleDateFormat("_yyyy-MM-dd_");
String dateString = formatter.format(new Date(time));
if (fileInterval == 24 * 3600000)
{
addon = dateString + "daily";
}
else if (fileInterval == 168 * 3600000)
{
addon = dateString + "weekly";
}
File file = new File(dir, "myTrack"+addon+".plt");
if (! file.exists())
{
file.createNewFile();
needsHeader = true;
}
if (file.canWrite())
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString(getString(R.string.trk_current), file.getName());
editor.commit();
trackWriter = new BufferedWriter(new FileWriter(file, true));
if (needsHeader)
{
trackWriter.write("OziExplorer Track Point File Version 2.1\n" +
"WGS 84\n" +
"Altitude is in Feet\n" +
"Reserved 3\n" +
// Field 1 : always zero (0)
// Field 2 : width of track plot line on screen - 1 or 2 are usually the best
// Field 3 : track color (RGB)
// Field 4 : track description (no commas allowed)
// Field 5 : track skip value - reduces number of track points plotted, usually set to 1
// Field 6 : track type - 0 = normal , 10 = closed polygon , 20 = Alarm Zone
// Field 7 : track fill style - 0 =bsSolid; 1 =bsClear; 2 =bsBdiagonal; 3 =bsFdiagonal; 4 =bsCross;
// 5 =bsDiagCross; 6 =bsHorizontal; 7 =bsVertical;
// Field 8 : track fill color (RGB)
"0,2," +
OziExplorerFiles.rgb2bgr(color) +
",Androzic Current Track " + addon +
" ,0,0\n" +
"0\n");
needsHeader = false;
}
}
else
{
showErrorNotification();
return;
}
}
catch (IOException e)
{
Log.e(TAG, e.toString(), e);
showErrorNotification();
return;
}
}
@Override
public void onDestroy()
{
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
closeFile();
unregisterReceiver(broadcastReceiver);
disconnect();
stopForeground(true);
notification = null;
contentIntent = null;
Log.i(TAG, "Service stopped");
}
private void connect()
{
bindService(new Intent(this, LocationService.class), locationConnection, BIND_AUTO_CREATE);
}
private void disconnect()
{
if (locationService != null)
{
locationService.unregisterCallback(locationListener);
unbindService(locationConnection);
locationService = null;
}
}
private void doStart()
{
if (isSuspended)
{
if (trackingEnabled)
{
startForeground(NOTIFICATION_ID, notification);
sendBroadcast(new Intent(BROADCAST_TRACKING_STATUS));
}
isSuspended = false;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.e(TAG, "Broadcast: " + action);
if (action.equals(LocationService.BROADCAST_LOCATING_STATUS))
{
if (locationService != null && locationService.isLocating())
{
doStart();
}
else if (trackingEnabled)
{
stopForeground(true);
closeFile();
isSuspended = true;
}
}
}
};
private void prepareNormalNotification()
{
notification.when = 0;
notification.icon = R.drawable.ic_stat_track;
notification.setLatestEventInfo(getApplicationContext(), getText(R.string.notif_trk_short), getText(R.string.notif_trk_started), contentIntent);
errorState = false;
}
private void showErrorNotification()
{
if (errorState)
return;
notification.when = System.currentTimeMillis();
notification.defaults |= Notification.DEFAULT_SOUND;
/*
* Red icon (white): saturation +100, lightness -40
* Red icon (grey): saturation +100, lightness 0
*/
notification.icon = R.drawable.ic_stat_track_error;
notification.setLatestEventInfo(getApplicationContext(), getText(R.string.notif_trk_short), getText(R.string.err_currentlog), contentIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, notification);
errorState = true;
}
public void addPoint(boolean continous, double latitude, double longitude, double altitude, float speed, long time)
{
long interval = fileInterval > 0 ? time % fileInterval : -1;
if (interval == 0 || trackWriter == null)
{
createFile(time);
}
try
{
//Field 1 : Latitude - decimal degrees.
//Field 2 : Longitude - decimal degrees.
//Field 3 : Code - 0 if normal, 1 if break in track line
//Field 4 : Altitude in feet (-777 if not valid)
//Field 5 : Date - see Date Format below, if blank a preset date will be used
//Field 6 : Date as a string
//Field 7 : Time as a string
// Note that OziExplorer reads the Date/Time from field 5, the date and time in fields 6 & 7 are ignored.
//-27.350436, 153.055540,1,-777,36169.6307194, 09-Jan-99, 3:08:14
trackWriter.write(coordFormat.format(latitude)+","+coordFormat.format(longitude)+",");
if (continous)
trackWriter.write("0");
else
trackWriter.write("1");
trackWriter.write(","+String.valueOf(Math.round(altitude * 3.2808399)));
trackWriter.write(","+String.valueOf(TDateTime.toDateTime(time)));
trackWriter.write("\n");
}
catch (Exception e)
{
showErrorNotification();
closeFile();
}
}
private void writeLocation(final Location loc, final boolean continous)
{
Log.d(TAG, "Fix needs writing");
lastWritenLocation = loc;
distanceFromLastWriting = 0;
addPoint(continous, loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getSpeed(), loc.getTime());
for (ITrackingListener callback : callbacks)
{
callback.onNewPoint(continous, loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getSpeed(), loc.getBearing(), loc.getTime());
}
final int n = remoteCallbacks.beginBroadcast();
for (int i=0; i<n; i++)
{
final ITrackingCallback callback = remoteCallbacks.getBroadcastItem(i);
try
{
callback.onNewPoint(continous, loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getSpeed(), loc.getBearing(), loc.getTime());
}
catch (RemoteException e)
{
Log.e(TAG, "Point broadcast error", e);
}
}
remoteCallbacks.finishBroadcast();
}
private ServiceConnection locationConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service)
{
locationService = (ILocationService) service;
locationService.registerCallback(locationListener);
if (locationService.isLocating())
doStart();
Log.i(TAG, "Location service connected");
}
public void onServiceDisconnected(ComponentName className)
{
locationService = null;
Log.i(TAG, "Location service disconnected");
}
};
private ILocationListener locationListener = new ILocationListener()
{
@Override
public void onGpsStatusChanged(String provider, int status, int fsats, int tsats)
{
if (LocationManager.GPS_PROVIDER.equals(provider))
{
switch (status)
{
case LocationService.GPS_OFF:
case LocationService.GPS_SEARCHING:
if (lastLocation != null && (lastWritenLocation == null || ! lastLocation.toString().equals(lastWritenLocation.toString())))
writeLocation(lastLocation, isContinous);
isContinous = false;
}
}
}
@Override
public void onLocationChanged(Location loc, boolean continous, boolean geoid, float smoothspeed, float avgspeed)
{
Log.d(TAG, "Location arrived");
boolean needsWrite = false;
if (lastLocation != null)
{
distanceFromLastWriting += loc.distanceTo(lastLocation);
}
if (lastWritenLocation != null)
timeFromLastWriting = loc.getTime() - lastWritenLocation.getTime();
if (lastLocation == null ||
lastWritenLocation == null ||
! isContinous ||
timeFromLastWriting > maxTime ||
distanceFromLastWriting > minDistance && timeFromLastWriting > minTime)
{
needsWrite = true;
}
lastLocation = loc;
if (needsWrite && ! isSuspended)
{
writeLocation(loc, isContinous);
isContinous = continous;
}
}
@Override
public void onProviderChanged(String provider)
{
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onSensorChanged(float azimuth, float pitch, float roll)
{
}
};
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (getString(R.string.pref_tracking_currentcolor).equals(key))
{
color = sharedPreferences.getInt(key, getResources().getColor(R.color.currenttrack));
}
else if (getString(R.string.pref_tracking_mintime).equals(key))
{
try
{
minTime = Integer.parseInt(sharedPreferences.getString(key, "500"));
}
catch (NumberFormatException e)
{
}
}
else if (getString(R.string.pref_tracking_mindistance).equals(key))
{
try
{
minDistance = Integer.parseInt(sharedPreferences.getString(key, "5"));
}
catch (NumberFormatException e)
{
}
}
else if (getString(R.string.pref_tracking_currentinterval).equals(key))
{
try
{
fileInterval = Integer.parseInt(sharedPreferences.getString(key, "0")) * 3600000;
}
catch (NumberFormatException e)
{
fileInterval = 0;
}
closeFile();
}
else if (getString(R.string.pref_folder_track).equals(key))
{
closeFile();
}
}
private final ITrackingRemoteService.Stub remoteBinder = new ITrackingRemoteService.Stub()
{
public void registerCallback(ITrackingCallback cb)
{
Log.i(TAG, "Register callback");
if (cb != null) remoteCallbacks.register(cb);
}
public void unregisterCallback(ITrackingCallback cb)
{
if (cb != null) remoteCallbacks.unregister(cb);
}
};
@Override
public IBinder onBind(Intent intent)
{
if ("com.androzic.tracking".equals(intent.getAction()) || ITrackingRemoteService.class.getName().equals(intent.getAction()))
{
return remoteBinder;
}
else
{
return binder;
}
}
public class LocalBinder extends Binder implements ITrackingService
{
@Override
public void registerCallback(ITrackingListener callback)
{
callbacks.add(callback);
}
@Override
public void unregisterCallback(ITrackingListener callback)
{
callbacks.remove(callback);
}
@Override
public boolean isTracking()
{
return trackingEnabled;
}
}
}
| true | true | private void createFile(long time)
{
closeFile();
try
{
Androzic application = Androzic.getApplication();
File dir = new File(application.trackPath);
if (! dir.exists())
dir.mkdirs();
String addon = "";
SimpleDateFormat formatter = new SimpleDateFormat("_yyyy-MM-dd_");
String dateString = formatter.format(new Date(time));
if (fileInterval == 24 * 3600000)
{
addon = dateString + "daily";
}
else if (fileInterval == 168 * 3600000)
{
addon = dateString + "weekly";
}
File file = new File(dir, "myTrack"+addon+".plt");
if (! file.exists())
{
file.createNewFile();
needsHeader = true;
}
if (file.canWrite())
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString(getString(R.string.trk_current), file.getName());
editor.commit();
trackWriter = new BufferedWriter(new FileWriter(file, true));
if (needsHeader)
{
trackWriter.write("OziExplorer Track Point File Version 2.1\n" +
"WGS 84\n" +
"Altitude is in Feet\n" +
"Reserved 3\n" +
// Field 1 : always zero (0)
// Field 2 : width of track plot line on screen - 1 or 2 are usually the best
// Field 3 : track color (RGB)
// Field 4 : track description (no commas allowed)
// Field 5 : track skip value - reduces number of track points plotted, usually set to 1
// Field 6 : track type - 0 = normal , 10 = closed polygon , 20 = Alarm Zone
// Field 7 : track fill style - 0 =bsSolid; 1 =bsClear; 2 =bsBdiagonal; 3 =bsFdiagonal; 4 =bsCross;
// 5 =bsDiagCross; 6 =bsHorizontal; 7 =bsVertical;
// Field 8 : track fill color (RGB)
"0,2," +
OziExplorerFiles.rgb2bgr(color) +
",Androzic Current Track " + addon +
" ,0,0\n" +
"0\n");
needsHeader = false;
}
}
else
{
showErrorNotification();
return;
}
}
catch (IOException e)
{
Log.e(TAG, e.toString(), e);
showErrorNotification();
return;
}
}
| private void createFile(long time)
{
closeFile();
try
{
Androzic application = Androzic.getApplication();
if (application.trackPath == null)
return;
File dir = new File(application.trackPath);
if (! dir.exists())
dir.mkdirs();
String addon = "";
SimpleDateFormat formatter = new SimpleDateFormat("_yyyy-MM-dd_");
String dateString = formatter.format(new Date(time));
if (fileInterval == 24 * 3600000)
{
addon = dateString + "daily";
}
else if (fileInterval == 168 * 3600000)
{
addon = dateString + "weekly";
}
File file = new File(dir, "myTrack"+addon+".plt");
if (! file.exists())
{
file.createNewFile();
needsHeader = true;
}
if (file.canWrite())
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString(getString(R.string.trk_current), file.getName());
editor.commit();
trackWriter = new BufferedWriter(new FileWriter(file, true));
if (needsHeader)
{
trackWriter.write("OziExplorer Track Point File Version 2.1\n" +
"WGS 84\n" +
"Altitude is in Feet\n" +
"Reserved 3\n" +
// Field 1 : always zero (0)
// Field 2 : width of track plot line on screen - 1 or 2 are usually the best
// Field 3 : track color (RGB)
// Field 4 : track description (no commas allowed)
// Field 5 : track skip value - reduces number of track points plotted, usually set to 1
// Field 6 : track type - 0 = normal , 10 = closed polygon , 20 = Alarm Zone
// Field 7 : track fill style - 0 =bsSolid; 1 =bsClear; 2 =bsBdiagonal; 3 =bsFdiagonal; 4 =bsCross;
// 5 =bsDiagCross; 6 =bsHorizontal; 7 =bsVertical;
// Field 8 : track fill color (RGB)
"0,2," +
OziExplorerFiles.rgb2bgr(color) +
",Androzic Current Track " + addon +
" ,0,0\n" +
"0\n");
needsHeader = false;
}
}
else
{
showErrorNotification();
return;
}
}
catch (IOException e)
{
Log.e(TAG, e.toString(), e);
showErrorNotification();
return;
}
}
|
diff --git a/x10.compiler/src/x10/ast/AssignPropertyCall_c.java b/x10.compiler/src/x10/ast/AssignPropertyCall_c.java
index 76e68034d..2ebd461d0 100644
--- a/x10.compiler/src/x10/ast/AssignPropertyCall_c.java
+++ b/x10.compiler/src/x10/ast/AssignPropertyCall_c.java
@@ -1,380 +1,381 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10.ast;
import java.util.ArrayList;
import java.util.List;
import polyglot.ast.Assign;
import polyglot.ast.Expr;
import polyglot.ast.FieldAssign;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.Stmt;
import polyglot.ast.Stmt_c;
import polyglot.ast.Term;
import polyglot.ast.TypeNode;
import polyglot.frontend.Job;
import polyglot.types.ClassType;
import polyglot.types.Context;
import polyglot.types.FieldInstance;
import polyglot.types.LocalInstance;
import polyglot.types.Ref;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.types.UnknownType;
import polyglot.util.Position;
import polyglot.util.TypedList;
import polyglot.visit.CFGBuilder;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import polyglot.visit.TypeBuilder;
import x10.Configuration;
import x10.constraint.XFailure;
import x10.constraint.XTerms;
import x10.constraint.XVar;
import x10.constraint.XTerm;
import x10.constraint.XVar;
import x10.errors.Errors;
import x10.errors.Errors.IllegalConstraint;
import x10.types.X10ConstructorDef;
import polyglot.types.Context;
import x10.types.X10ClassType;
import x10.types.X10FieldInstance;
import x10.types.X10ParsedClassType;
import polyglot.types.TypeSystem;
import x10.types.XTypeTranslator;
import x10.types.X10ClassDef;
import x10.types.X10TypeEnv;
import x10.types.X10TypeEnv_c;
import x10.types.checker.ThisChecker;
import x10.types.constraints.CConstraint;
import x10.types.constraints.CConstraint;
import x10.types.constraints.CTerms;
import x10.types.constraints.ConstraintMaker;
import x10.types.matcher.Matcher;
/**
* @author vj
* @author igor
*/
public class AssignPropertyCall_c extends Stmt_c implements AssignPropertyCall {
List<Expr> arguments;
List<X10FieldInstance> properties;
/**
* @param pos
* @param arguments
* @param target
* @param name
*/
public AssignPropertyCall_c(Position pos, List<Expr> arguments) {
super(pos);
this.arguments = TypedList.copyAndCheck(arguments, Expr.class, true);
}
public Term firstChild() {
return listChild(arguments, null);
}
/* (non-Javadoc)
* @see polyglot.ast.Term#acceptCFG(polyglot.visit.CFGBuilder, java.util.List)
*/
public <S> List<S> acceptCFG(CFGBuilder v, List<S> succs) {
v.visitCFGList(arguments, this, EXIT);
return succs;
}
public AssignPropertyCall arguments(List<Expr> args) {
if (args == arguments) return this;
AssignPropertyCall_c n = (AssignPropertyCall_c) copy();
n.arguments = TypedList.copyAndCheck(args, Expr.class, true);
return n;
}
public List<Expr> arguments() {
return arguments;
}
public AssignPropertyCall properties(List<X10FieldInstance> properties) {
if (properties == this.properties) return this;
AssignPropertyCall_c n = (AssignPropertyCall_c) copy();
n.properties = TypedList.copyAndCheck(properties, FieldInstance.class, true);
return n;
}
public List<X10FieldInstance> properties() {
return properties;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("property");
sb.append("(");
boolean first = true;
for (Expr e : arguments) {
if (first) {
first = false;
}
else {
sb.append(", ");
}
sb.append(e);
}
sb.append(");");
return sb.toString();
}
public static X10ConstructorDef getConstructorDef(TypeBuilder tb) {
for (; tb != null && tb.inCode(); tb = tb.pop())
if (tb.def() instanceof X10ConstructorDef)
return (X10ConstructorDef) tb.def();
return null;
}
@Override
public Node buildTypes(TypeBuilder tb) {
X10ConstructorDef cd = getConstructorDef(tb);
if (cd != null) {
cd.derivedReturnType(true);
}
return this;
}
@Override
public Node typeCheck(ContextVisitor tc) {
TypeSystem ts = tc.typeSystem();
Context ctx = tc.context();
NodeFactory nf = (NodeFactory) tc.nodeFactory();
Position pos = position();
Job job = tc.job();
X10ConstructorDef thisConstructor = ctx.getCtorIgnoringAsync();
X10ParsedClassType container = (X10ParsedClassType) ctx.currentClass();
if (thisConstructor==null) {
Errors.issue(job,
new Errors.PropertyStatementMayOnlyOccurInBodyOfConstuctor(position()));
} else {
container = (X10ParsedClassType) thisConstructor.asInstance().container();
}
// Now check that the types of each actual argument are subtypes of the corresponding
// property for the class reachable through the constructor.
List<FieldInstance> definedProperties = container.definedProperties();
int pSize = definedProperties.size();
int aSize = arguments.size();
if (aSize != pSize) {
Errors.issue(job,
new Errors.PropertyInitializerMustHaveSameNumberOfArgumentsAsPropertyForClass(position()));
}
checkAssignments(tc, pos, definedProperties, arguments);
if (thisConstructor != null) {
checkReturnType(tc, pos, thisConstructor, definedProperties, arguments);
}
/* We check that "this" is not allowed in CheckEscapingThis.CheckCtor
ThisChecker thisC = (ThisChecker) new ThisChecker(tc.job()).context(tc.context());
for (int i=0; i < aSize; i++) {
Expr arg = arguments.get(i);
thisC.clearError();
visitChild(arg, thisC);
if (thisC.error()) {
Errors.issue(job, new Errors.ThisNotPermittedInPropertyInitializer(arg, position()));
}
} */
List<X10FieldInstance> properties = new ArrayList<X10FieldInstance>();
for (FieldInstance fi : definedProperties) {
properties.add((X10FieldInstance) fi);
}
return this.properties(properties);
}
protected static void checkAssignments(ContextVisitor tc, Position pos,
List<FieldInstance> props, List<Expr> args)
{
TypeSystem xts = tc.typeSystem();
Context cxt = tc.context();
XVar thisVar = tc.context().thisVar();
Type thisType=null;
// Accumulate in curr constraint the bindings {arg1==this.prop1,..argi==this.propi}.
// If argi does not have a name, make up a name, and add the constraint from typei
// into curr, with argi/self.
CConstraint curr = new CConstraint();
for (int i=0; i < args.size() && i < props.size(); ++i) {
Type yType = args.get(i).type();
yType = Types.addConstraint(yType, curr);
Type xType = props.get(i).type();
if (!xts.isSubtype(yType, xType)) {
Errors.issue(tc.job(),
new Errors.TypeOfPropertyIsNotSubtypeOfPropertyType(args.get(i).type(), props, i, pos));
}
XVar symbol = Types.selfVarBinding(yType);
if (symbol==null) {
symbol = XTerms.makeUQV();
CConstraint c = Types.xclause(yType);
curr.addIn(symbol, c);
}
curr.addBinding(CTerms.makeField(thisVar, props.get(i).def()), symbol);
if (! curr.consistent()) {
Errors.issue(tc.job(),
new SemanticException("Inconsistent environment for property assignment call.", pos));
}
}
if (! curr.valid()) {
curr.addIn(cxt.currentConstraint());
cxt.setCurrentConstraint(curr);
}
}
protected void checkReturnType(ContextVisitor tc, Position pos,
X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties,
List<Expr> args)
{
TypeSystem ts = tc.typeSystem();
final Context ctx = tc.context();
if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) {
return;
}
Type returnType = Types.getCached(thisConstructor.returnType());
CConstraint result = Types.xclause(returnType);
if (result != null && result.valid())
result = null;
// FIXME: the code below that infers the return type of a ctor is buggy,
// since it infers "this". see XTENLANG-1770
{
Type supType = thisConstructor.supType();
CConstraint known = Types.realX(supType);
known = (known==null ? new CConstraint() : known.copy());
try {
known.addIn(Types.get(thisConstructor.guard()));
XVar thisVar = thisConstructor.thisVar();
for (int i = 0; i < args.size() && i < definedProperties.size(); i++) {
Expr initializer = args.get(i);
Type initType = initializer.type();
final FieldInstance fii = definedProperties.get(i);
XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii);
// Add in the real clause of the initializer with [self.prop/self]
CConstraint c = Types.realX(initType);
if (! c.consistent()) {
Errors.issue(tc.job(),
new Errors.InconsistentContext(initType, pos));
}
if (c != null)
known.addIn(c.substitute(prop, c.self()));
try {
XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar"
if (initVar != null)
known.addBinding(prop, initVar);
} catch (IllegalConstraint z) {
Errors.issue(tc.job(), z);
}
}
X10ConstructorCall_c.checkSuperType(tc,supType, position);
// Set the return type of the enclosing constructor to be this inferred type.
Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known);
inferredResultType = Types.removeLocals( tc.context(), inferredResultType);
if (! Types.consistent(inferredResultType)) {
Errors.issue(tc.job(),
new Errors.InconsistentType(inferredResultType, pos));
}
Ref <? extends Type> r = thisConstructor.returnType();
((Ref<Type>) r).update(inferredResultType);
// bind this==self; sup clause may constrain this.
if (thisVar != null) {
known = known.instantiateSelf(thisVar);
// known.addSelfBinding(thisVar);
// known.setThisVar(thisVar);
}
final CConstraint k = known;
if (result != null) {
final CConstraint rr = result.instantiateSelf(thisVar);
if (!k.entails(rr, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, rr);
}}))
Errors.issue(tc.job(),
new Errors.ConstructorReturnTypeNotEntailed(known, result, pos));
}
// Check that the class invariant is satisfied.
X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx);
CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy();
X10TypeEnv env = ts.env(tc.context());
boolean isThis = true; // because in the class invariant we use this (and not self)
X10TypeEnv_c env_c = (X10TypeEnv_c) env;
_inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv);
final CConstraint inv = _inv;
if (!k.entails(inv, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, inv);
}}))
Errors.issue(tc.job(),
new Errors.InvariantNotEntailed(known, inv, pos));
// Check that every super interface is entailed.
for (Type intfc : ctype.interfaces()) {
CConstraint cc = Types.realX(intfc);
+ cc = cc.substitute(thisVar, cc.self()); // for some reason, the invariant has "self" instead of this, so I fix it here.
if (thisVar != null) {
XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar();
cc = cc.substitute(thisVar, intfcThisVar);
}
- cc = X10TypeEnv_c.ifNull(env_c.expandProperty(false,ctype,cc),cc); // for some reason we have self in the invariant, see InterfaceTypeInvariant
+ cc = X10TypeEnv_c.ifNull(env_c.expandProperty(true,ctype,cc),cc);
final CConstraint ccc=cc;
if (!k.entails(cc, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, ccc);
}}))
Errors.issue(tc.job(),
new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos));
}
// Install the known constraint in the context.
CConstraint c = ctx.currentConstraint();
known.addIn(c);
ctx.setCurrentConstraint(known);
}
catch (XFailure e) {
Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this);
}
}
}
/** Visit the children of the statement. */
public Node visitChildren(NodeVisitor v) {
List<Expr> args = visitList(this.arguments, v);
return arguments(args);
}
}
| false | true | protected void checkReturnType(ContextVisitor tc, Position pos,
X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties,
List<Expr> args)
{
TypeSystem ts = tc.typeSystem();
final Context ctx = tc.context();
if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) {
return;
}
Type returnType = Types.getCached(thisConstructor.returnType());
CConstraint result = Types.xclause(returnType);
if (result != null && result.valid())
result = null;
// FIXME: the code below that infers the return type of a ctor is buggy,
// since it infers "this". see XTENLANG-1770
{
Type supType = thisConstructor.supType();
CConstraint known = Types.realX(supType);
known = (known==null ? new CConstraint() : known.copy());
try {
known.addIn(Types.get(thisConstructor.guard()));
XVar thisVar = thisConstructor.thisVar();
for (int i = 0; i < args.size() && i < definedProperties.size(); i++) {
Expr initializer = args.get(i);
Type initType = initializer.type();
final FieldInstance fii = definedProperties.get(i);
XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii);
// Add in the real clause of the initializer with [self.prop/self]
CConstraint c = Types.realX(initType);
if (! c.consistent()) {
Errors.issue(tc.job(),
new Errors.InconsistentContext(initType, pos));
}
if (c != null)
known.addIn(c.substitute(prop, c.self()));
try {
XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar"
if (initVar != null)
known.addBinding(prop, initVar);
} catch (IllegalConstraint z) {
Errors.issue(tc.job(), z);
}
}
X10ConstructorCall_c.checkSuperType(tc,supType, position);
// Set the return type of the enclosing constructor to be this inferred type.
Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known);
inferredResultType = Types.removeLocals( tc.context(), inferredResultType);
if (! Types.consistent(inferredResultType)) {
Errors.issue(tc.job(),
new Errors.InconsistentType(inferredResultType, pos));
}
Ref <? extends Type> r = thisConstructor.returnType();
((Ref<Type>) r).update(inferredResultType);
// bind this==self; sup clause may constrain this.
if (thisVar != null) {
known = known.instantiateSelf(thisVar);
// known.addSelfBinding(thisVar);
// known.setThisVar(thisVar);
}
final CConstraint k = known;
if (result != null) {
final CConstraint rr = result.instantiateSelf(thisVar);
if (!k.entails(rr, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, rr);
}}))
Errors.issue(tc.job(),
new Errors.ConstructorReturnTypeNotEntailed(known, result, pos));
}
// Check that the class invariant is satisfied.
X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx);
CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy();
X10TypeEnv env = ts.env(tc.context());
boolean isThis = true; // because in the class invariant we use this (and not self)
X10TypeEnv_c env_c = (X10TypeEnv_c) env;
_inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv);
final CConstraint inv = _inv;
if (!k.entails(inv, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, inv);
}}))
Errors.issue(tc.job(),
new Errors.InvariantNotEntailed(known, inv, pos));
// Check that every super interface is entailed.
for (Type intfc : ctype.interfaces()) {
CConstraint cc = Types.realX(intfc);
if (thisVar != null) {
XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar();
cc = cc.substitute(thisVar, intfcThisVar);
}
cc = X10TypeEnv_c.ifNull(env_c.expandProperty(false,ctype,cc),cc); // for some reason we have self in the invariant, see InterfaceTypeInvariant
final CConstraint ccc=cc;
if (!k.entails(cc, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, ccc);
}}))
Errors.issue(tc.job(),
new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos));
}
// Install the known constraint in the context.
CConstraint c = ctx.currentConstraint();
known.addIn(c);
ctx.setCurrentConstraint(known);
}
catch (XFailure e) {
Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this);
}
}
}
| protected void checkReturnType(ContextVisitor tc, Position pos,
X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties,
List<Expr> args)
{
TypeSystem ts = tc.typeSystem();
final Context ctx = tc.context();
if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) {
return;
}
Type returnType = Types.getCached(thisConstructor.returnType());
CConstraint result = Types.xclause(returnType);
if (result != null && result.valid())
result = null;
// FIXME: the code below that infers the return type of a ctor is buggy,
// since it infers "this". see XTENLANG-1770
{
Type supType = thisConstructor.supType();
CConstraint known = Types.realX(supType);
known = (known==null ? new CConstraint() : known.copy());
try {
known.addIn(Types.get(thisConstructor.guard()));
XVar thisVar = thisConstructor.thisVar();
for (int i = 0; i < args.size() && i < definedProperties.size(); i++) {
Expr initializer = args.get(i);
Type initType = initializer.type();
final FieldInstance fii = definedProperties.get(i);
XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii);
// Add in the real clause of the initializer with [self.prop/self]
CConstraint c = Types.realX(initType);
if (! c.consistent()) {
Errors.issue(tc.job(),
new Errors.InconsistentContext(initType, pos));
}
if (c != null)
known.addIn(c.substitute(prop, c.self()));
try {
XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar"
if (initVar != null)
known.addBinding(prop, initVar);
} catch (IllegalConstraint z) {
Errors.issue(tc.job(), z);
}
}
X10ConstructorCall_c.checkSuperType(tc,supType, position);
// Set the return type of the enclosing constructor to be this inferred type.
Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known);
inferredResultType = Types.removeLocals( tc.context(), inferredResultType);
if (! Types.consistent(inferredResultType)) {
Errors.issue(tc.job(),
new Errors.InconsistentType(inferredResultType, pos));
}
Ref <? extends Type> r = thisConstructor.returnType();
((Ref<Type>) r).update(inferredResultType);
// bind this==self; sup clause may constrain this.
if (thisVar != null) {
known = known.instantiateSelf(thisVar);
// known.addSelfBinding(thisVar);
// known.setThisVar(thisVar);
}
final CConstraint k = known;
if (result != null) {
final CConstraint rr = result.instantiateSelf(thisVar);
if (!k.entails(rr, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, rr);
}}))
Errors.issue(tc.job(),
new Errors.ConstructorReturnTypeNotEntailed(known, result, pos));
}
// Check that the class invariant is satisfied.
X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx);
CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy();
X10TypeEnv env = ts.env(tc.context());
boolean isThis = true; // because in the class invariant we use this (and not self)
X10TypeEnv_c env_c = (X10TypeEnv_c) env;
_inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv);
final CConstraint inv = _inv;
if (!k.entails(inv, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, inv);
}}))
Errors.issue(tc.job(),
new Errors.InvariantNotEntailed(known, inv, pos));
// Check that every super interface is entailed.
for (Type intfc : ctype.interfaces()) {
CConstraint cc = Types.realX(intfc);
cc = cc.substitute(thisVar, cc.self()); // for some reason, the invariant has "self" instead of this, so I fix it here.
if (thisVar != null) {
XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar();
cc = cc.substitute(thisVar, intfcThisVar);
}
cc = X10TypeEnv_c.ifNull(env_c.expandProperty(true,ctype,cc),cc);
final CConstraint ccc=cc;
if (!k.entails(cc, new ConstraintMaker() {
public CConstraint make() throws XFailure {
return ctx.constraintProjection(k, ccc);
}}))
Errors.issue(tc.job(),
new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos));
}
// Install the known constraint in the context.
CConstraint c = ctx.currentConstraint();
known.addIn(c);
ctx.setCurrentConstraint(known);
}
catch (XFailure e) {
Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this);
}
}
}
|
diff --git a/cmd/src/iumfs/CreateRequest.java b/cmd/src/iumfs/CreateRequest.java
old mode 100644
new mode 100755
index 060a697..2e4eea7
--- a/cmd/src/iumfs/CreateRequest.java
+++ b/cmd/src/iumfs/CreateRequest.java
@@ -1,39 +1,43 @@
/*
* Copyright 2011 Kazuyoshi Aizawa
*
* 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 iumfs;
import java.io.IOException;
/**
* <p>CREATE Request Class</p>
*/
public class CreateRequest extends Request {
/**
* <p>Excecute FileSystem.create</p>
* <p>
* </p>
*/
@Override
public void execute() throws IOException {
IumfsFile file = getFile();
+ if (file == null) {
+ setResponseHeader(ENOENT, 0);
+ return;
+ }
file.create();
/*
* レスポンスヘッダをセット
*/
setResponseHeader(SUCCESS, 0);
}
}
| true | true | public void execute() throws IOException {
IumfsFile file = getFile();
file.create();
/*
* レスポンスヘッダをセット
*/
setResponseHeader(SUCCESS, 0);
}
| public void execute() throws IOException {
IumfsFile file = getFile();
if (file == null) {
setResponseHeader(ENOENT, 0);
return;
}
file.create();
/*
* レスポンスヘッダをセット
*/
setResponseHeader(SUCCESS, 0);
}
|
diff --git a/DistFileSystem/src/distmain/DistFileSystemMain.java b/DistFileSystem/src/distmain/DistFileSystemMain.java
index 9a15359..dde7698 100644
--- a/DistFileSystem/src/distmain/DistFileSystemMain.java
+++ b/DistFileSystem/src/distmain/DistFileSystemMain.java
@@ -1,137 +1,148 @@
/**
* @author paul
*/
package distmain;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import distclient.*;
import distfilelisting.UserManagement;
import distnodelisting.NodeSearchTable;
import distserver.Server;
public class DistFileSystemMain {
private String prompt = "%s : ";
private BufferedReader inStream;
private UserManagement userManage = null;
private NodeSearchTable nst = null;
private String ipAddress = null;
private Thread thServ = null;
private Vector<Thread> backgrounded = new Vector<Thread>();
public DistFileSystemMain () {
try {
inStream = new BufferedReader(new InputStreamReader(System.in));
userManage = UserManagement.get_Instance();
nst = NodeSearchTable.get_Instance();
System.out.print("Username: ");
String userName = inStream.readLine();
userManage.set_ownUserName(userName);
System.out.print("IP Of Net: ");
ipAddress = inStream.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
this.start_server();
// If IP address was given, connect to existing network
// Otherwise this will
if (!ipAddress.equals(""))
this.connect_to_network();
this.run_interface();
}
public void start_server() {
System.out.println("Starting Server");
Server serv = new Server();
thServ = new Thread (serv);
thServ.start();
}
public void connect_to_network() {
try {
int nextID;
String nextIP;
Client cli = new Client();
// Connect to the network and get initial search location
+ // These have to all run in the same thread since they rely on each other
System.out.printf("Connecting to %s\n", ipAddress);
- cli.addTask(new ClntEnterNetwork(ipAddress, cli));
+ ClntEnterNetwork cen = new ClntEnterNetwork(ipAddress, cli);
+ cen.run();
+ cen = null;
nextID = cli.getServId();
nextIP = cli.getServIp();
// Locate the servers location
- System.out.printf("Entering netwrok at %s\n", nextIP);
- cli.addTask(new ClntCheckPosition(nextIP, nextID, cli));
+ System.out.printf("Entering network at %s\n", nextIP);
+ ClntCheckPosition ccp = new ClntCheckPosition(nextIP, nextID, cli);
+ ccp.run();
+ ccp = null;
String[] pred = cli.getPredecessor();
String[] succ = cli.getSuccessor();
// Connect to the predecessor
System.out.printf("Connecting to predecessor %s\n", pred[1]);
- cli.addTask(new ClntNewPredecessor(cli));
+ ClntNewPredecessor cnp = new ClntNewPredecessor(cli);
+ cnp.run();
+ cnp = null;
// Connect to the successor
System.out.printf("Connecting to successor %s\n", succ[1]);
- cli.addTask(new ClntNewSuccessor(cli));
+ ClntNewSuccessor cns = new ClntNewSuccessor(cli);
+ cns.run();
+ cns = null;
// Send new node notification
System.out.printf("Sending the new node notification\n");
- cli.addTask(new ClntNewNode(succ[1]));
+ ClntNewNode cnn = new ClntNewNode(succ[1]);
+ cnn.run();
+ cnn = null;
System.out.println ("Connected to the network\n");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
public void run_interface() {
String input;
boolean exit = false;
while (!exit) {
try {
System.out.printf(this.prompt, this.userManage.get_ownUserName());
input = inStream.readLine();
if (input.equals("view predecessor")) {
System.out.printf("Predecessor ID = %s\n", this.nst.get_predecessorID());
System.out.printf("Predecessor IP = %s\n", this.nst.get_predecessorIPAddress());
}
else if (input.equals("view node search table")) {
for(int index = 0; index < this.nst.size(); index++) {
System.out.printf("Entry: %d\tID: %s\tIP: %s\n",
index, this.nst.get_IDAt(index), this.nst.get_IPAt(index));
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main (String[] args) {
DistFileSystemMain dfsm = new DistFileSystemMain();
}
}
| false | true | public void connect_to_network() {
try {
int nextID;
String nextIP;
Client cli = new Client();
// Connect to the network and get initial search location
System.out.printf("Connecting to %s\n", ipAddress);
cli.addTask(new ClntEnterNetwork(ipAddress, cli));
nextID = cli.getServId();
nextIP = cli.getServIp();
// Locate the servers location
System.out.printf("Entering netwrok at %s\n", nextIP);
cli.addTask(new ClntCheckPosition(nextIP, nextID, cli));
String[] pred = cli.getPredecessor();
String[] succ = cli.getSuccessor();
// Connect to the predecessor
System.out.printf("Connecting to predecessor %s\n", pred[1]);
cli.addTask(new ClntNewPredecessor(cli));
// Connect to the successor
System.out.printf("Connecting to successor %s\n", succ[1]);
cli.addTask(new ClntNewSuccessor(cli));
// Send new node notification
System.out.printf("Sending the new node notification\n");
cli.addTask(new ClntNewNode(succ[1]));
System.out.println ("Connected to the network\n");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
| public void connect_to_network() {
try {
int nextID;
String nextIP;
Client cli = new Client();
// Connect to the network and get initial search location
// These have to all run in the same thread since they rely on each other
System.out.printf("Connecting to %s\n", ipAddress);
ClntEnterNetwork cen = new ClntEnterNetwork(ipAddress, cli);
cen.run();
cen = null;
nextID = cli.getServId();
nextIP = cli.getServIp();
// Locate the servers location
System.out.printf("Entering network at %s\n", nextIP);
ClntCheckPosition ccp = new ClntCheckPosition(nextIP, nextID, cli);
ccp.run();
ccp = null;
String[] pred = cli.getPredecessor();
String[] succ = cli.getSuccessor();
// Connect to the predecessor
System.out.printf("Connecting to predecessor %s\n", pred[1]);
ClntNewPredecessor cnp = new ClntNewPredecessor(cli);
cnp.run();
cnp = null;
// Connect to the successor
System.out.printf("Connecting to successor %s\n", succ[1]);
ClntNewSuccessor cns = new ClntNewSuccessor(cli);
cns.run();
cns = null;
// Send new node notification
System.out.printf("Sending the new node notification\n");
ClntNewNode cnn = new ClntNewNode(succ[1]);
cnn.run();
cnn = null;
System.out.println ("Connected to the network\n");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
|
diff --git a/src/org/newdawn/slick/SpriteSheet.java b/src/org/newdawn/slick/SpriteSheet.java
index ad6418a..c9b943b 100644
--- a/src/org/newdawn/slick/SpriteSheet.java
+++ b/src/org/newdawn/slick/SpriteSheet.java
@@ -1,204 +1,204 @@
package org.newdawn.slick;
import java.io.InputStream;
/**
* A sheet of sprites that can be drawn individually
*
* @author Kevin Glass
*/
public class SpriteSheet extends Image {
/** The width of a single element in pixels */
private int tw;
/** The height of a single element in pixels */
private int th;
/** Subimages */
private Image[][] subImages;
/** The spacing between tiles */
private int spacing;
/** The target image for this sheet */
private Image target;
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
*/
public SpriteSheet(Image image,int tw,int th) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param spacing The spacing between tiles
*/
public SpriteSheet(Image image,int tw,int th,int spacing) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
this.spacing = spacing;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th) throws SlickException {
this(ref,tw,th,null);
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param col The colour to treat as transparent
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th, Color col) throws SlickException {
super(ref, false, FILTER_NEAREST, col);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* Create a new sprite sheet based on a image location
*
* @param name The name to give to the image in the image cache
* @param ref The stream from which we can load the image
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String name, InputStream ref,int tw,int th) throws SlickException {
super(ref,name,false);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* @see org.newdawn.slick.Image#initImpl()
*/
protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight() - th) / (th + spacing)) + 1;
- if (getHeight() - th % (th+spacing) != 0) {
+ if ((getHeight() - th) % (th+spacing) != 0) {
tilesDown++;
}
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
/**
* Get a sprite at a particular cell on the sprite sheet
*
* @param x The x position of the cell on the sprite sheet
* @param y The y position of the cell on the sprite sheet
* @return The single image from the sprite sheet
*/
public Image getSprite(int x, int y) {
target.init();
initImpl();
return target.getSubImage(x*(tw+spacing),y*(th+spacing),tw,th);
}
/**
* Get the number of sprites across the sheet
*
* @return The number of sprites across the sheet
*/
public int getHorizontalCount() {
target.init();
initImpl();
return subImages.length;
}
/**
* Get the number of sprites down the sheet
*
* @return The number of sprite down the sheet
*/
public int getVerticalCount() {
target.init();
initImpl();
return subImages[0].length;
}
/**
* Render a sprite when this sprite sheet is in use.
*
* @see #startUse()
* @see #endUse()
*
* @param x The x position to render the sprite at
* @param y The y position to render the sprite at
* @param sx The x location of the cell to render
* @param sy The y location of the cell to render
*/
public void renderInUse(int x,int y,int sx,int sy) {
subImages[sx][sy].drawEmbedded(x, y, tw, th);
}
/**
* @see org.newdawn.slick.Image#endUse()
*/
public void endUse() {
if (target == this) {
super.endUse();
return;
}
target.endUse();
}
/**
* @see org.newdawn.slick.Image#startUse()
*/
public void startUse() {
if (target == this) {
super.startUse();
return;
}
target.startUse();
}
}
| true | true | protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight() - th) / (th + spacing)) + 1;
if (getHeight() - th % (th+spacing) != 0) {
tilesDown++;
}
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
| protected void initImpl() {
if (subImages != null) {
return;
}
int tilesAcross = ((getWidth() - tw) / (tw + spacing)) + 1;
int tilesDown = ((getHeight() - th) / (th + spacing)) + 1;
if ((getHeight() - th) % (th+spacing) != 0) {
tilesDown++;
}
subImages = new Image[tilesAcross][tilesDown];
for (int x=0;x<tilesAcross;x++) {
for (int y=0;y<tilesDown;y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
|
diff --git a/src/main/java/com/nclodger/control/action/order/OrderFinishAction.java b/src/main/java/com/nclodger/control/action/order/OrderFinishAction.java
index e502abf..ef2174f 100644
--- a/src/main/java/com/nclodger/control/action/order/OrderFinishAction.java
+++ b/src/main/java/com/nclodger/control/action/order/OrderFinishAction.java
@@ -1,83 +1,83 @@
package com.nclodger.control.action.order;
import com.nclodger.control.action.Action;
import com.nclodger.domain.Order;
import com.nclodger.domain.PromoCode;
import com.nclodger.domain.User;
import com.nclodger.dao.PromoCodeDAO;
import com.nclodger.logic.UserFacadeInterface;
import com.nclodger.mail.MailConfirmation;
import com.nclodger.webservices.Hotel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created with IntelliJ IDEA.
* User: reshet
* Date: 11/16/13
* Time: 4:59 PM
* To change this template use File | Settings | File Templates.
*/
public class OrderFinishAction extends Action {
private double getPromoPercent(String promo){
return 0.20;
}
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-config.xml");
//check
- String promo = (String)request.getAttribute("promocode");
+ String promo =request.getParameter("promocode");
request.getSession().setAttribute("promocode", promo);
PromoCodeDAO pcDAO = (PromoCodeDAO) ctx.getBean("promocodeDAO");
PromoCode pm = null;
if(promo!=null) {
if(!pcDAO.isExist(promo)){
request.setAttribute("isExist",false);
return "orderstart";
}
else{
if(pcDAO.isUsed(promo)){
request.setAttribute("isUsed",true);
return "orderstart";
}
else{
if(pcDAO.isExpired(promo)){
request.setAttribute("isExpired",true);
return "orderstart";
}else{
//here promo is valid
pm = pcDAO.get(promo);
int b = 0;
}
}
}
}
UserFacadeInterface facade = (UserFacadeInterface) ctx.getBean("userFacade");
Hotel h = (Hotel)request.getSession().getAttribute("hotel");
User user = (User)request.getSession().getAttribute("userfull");
Order order = new Order();
order.setH(h);
order.setPromo(pm);
order.setUserid(user.getId());
order.setStart_date((String)request.getSession().getAttribute("checkindate"));
order.setEnd_date((String)request.getSession().getAttribute("checkoutdate"));
facade.calculateFinalPrice(order);
request.setAttribute("finalprice", order.getFinal_price());
facade.saveOrder(order);
//Double final_price = h.getRoomPrice() - h.getRoomPrice()*getPromoPercent(promo);
//request.setAttribute("finalprice", final_price);
return "orderfinish";
}
}
| true | true | public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-config.xml");
//check
String promo = (String)request.getAttribute("promocode");
request.getSession().setAttribute("promocode", promo);
PromoCodeDAO pcDAO = (PromoCodeDAO) ctx.getBean("promocodeDAO");
PromoCode pm = null;
if(promo!=null) {
if(!pcDAO.isExist(promo)){
request.setAttribute("isExist",false);
return "orderstart";
}
else{
if(pcDAO.isUsed(promo)){
request.setAttribute("isUsed",true);
return "orderstart";
}
else{
if(pcDAO.isExpired(promo)){
request.setAttribute("isExpired",true);
return "orderstart";
}else{
//here promo is valid
pm = pcDAO.get(promo);
int b = 0;
}
}
}
}
UserFacadeInterface facade = (UserFacadeInterface) ctx.getBean("userFacade");
Hotel h = (Hotel)request.getSession().getAttribute("hotel");
User user = (User)request.getSession().getAttribute("userfull");
Order order = new Order();
order.setH(h);
order.setPromo(pm);
order.setUserid(user.getId());
order.setStart_date((String)request.getSession().getAttribute("checkindate"));
order.setEnd_date((String)request.getSession().getAttribute("checkoutdate"));
facade.calculateFinalPrice(order);
request.setAttribute("finalprice", order.getFinal_price());
facade.saveOrder(order);
//Double final_price = h.getRoomPrice() - h.getRoomPrice()*getPromoPercent(promo);
//request.setAttribute("finalprice", final_price);
return "orderfinish";
}
| public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-config.xml");
//check
String promo =request.getParameter("promocode");
request.getSession().setAttribute("promocode", promo);
PromoCodeDAO pcDAO = (PromoCodeDAO) ctx.getBean("promocodeDAO");
PromoCode pm = null;
if(promo!=null) {
if(!pcDAO.isExist(promo)){
request.setAttribute("isExist",false);
return "orderstart";
}
else{
if(pcDAO.isUsed(promo)){
request.setAttribute("isUsed",true);
return "orderstart";
}
else{
if(pcDAO.isExpired(promo)){
request.setAttribute("isExpired",true);
return "orderstart";
}else{
//here promo is valid
pm = pcDAO.get(promo);
int b = 0;
}
}
}
}
UserFacadeInterface facade = (UserFacadeInterface) ctx.getBean("userFacade");
Hotel h = (Hotel)request.getSession().getAttribute("hotel");
User user = (User)request.getSession().getAttribute("userfull");
Order order = new Order();
order.setH(h);
order.setPromo(pm);
order.setUserid(user.getId());
order.setStart_date((String)request.getSession().getAttribute("checkindate"));
order.setEnd_date((String)request.getSession().getAttribute("checkoutdate"));
facade.calculateFinalPrice(order);
request.setAttribute("finalprice", order.getFinal_price());
facade.saveOrder(order);
//Double final_price = h.getRoomPrice() - h.getRoomPrice()*getPromoPercent(promo);
//request.setAttribute("finalprice", final_price);
return "orderfinish";
}
|
diff --git a/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java b/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java
index efbf86f..2b716d2 100644
--- a/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java
+++ b/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java
@@ -1,394 +1,394 @@
/**
* 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.hama.bsp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hama.Constants;
import org.apache.hama.bsp.sync.SyncClient;
import org.apache.hama.bsp.sync.SyncServiceFactory;
import org.apache.hama.checkpoint.CheckpointRunner;
import org.apache.hama.ipc.BSPPeerProtocol;
/**
* This class represents a BSP peer.
*/
public class BSPPeerImpl implements BSPPeer {
public static final Log LOG = LogFactory.getLog(BSPPeerImpl.class);
private final Configuration conf;
private BSPJob bspJob;
private volatile Server server = null;
private final Map<InetSocketAddress, BSPPeer> peers = new ConcurrentHashMap<InetSocketAddress, BSPPeer>();
private final Map<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>> outgoingQueues = new ConcurrentHashMap<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>>();
private ConcurrentLinkedQueue<BSPMessage> localQueue = new ConcurrentLinkedQueue<BSPMessage>();
private ConcurrentLinkedQueue<BSPMessage> localQueueForNextIteration = new ConcurrentLinkedQueue<BSPMessage>();
private final Map<String, InetSocketAddress> peerSocketCache = new ConcurrentHashMap<String, InetSocketAddress>();
private InetSocketAddress peerAddress;
private TaskStatus currentTaskStatus;
private TaskAttemptID taskId;
private BSPPeerProtocol umbilical;
private final BSPMessageSerializer messageSerializer;
private String[] allPeers;
private SyncClient syncClient;
/**
* Protected default constructor for LocalBSPRunner.
*/
protected BSPPeerImpl() {
messageSerializer = null;
conf = null;
}
/**
* BSPPeer Constructor.
*
* BSPPeer acts on behalf of clients performing bsp() tasks.
*
* @param conf is the configuration file containing bsp peer host, port, etc.
* @param umbilical is the bsp protocol used to contact its parent process.
* @param taskId is the id that current process holds.
* @throws Exception
*/
public BSPPeerImpl(BSPJob job, Configuration conf, TaskAttemptID taskId,
BSPPeerProtocol umbilical) throws Exception {
this.conf = conf;
this.taskId = taskId;
this.umbilical = umbilical;
this.bspJob = job;
String bindAddress = conf.get(Constants.PEER_HOST,
Constants.DEFAULT_PEER_HOST);
int bindPort = conf
.getInt(Constants.PEER_PORT, Constants.DEFAULT_PEER_PORT);
peerAddress = new InetSocketAddress(bindAddress, bindPort);
BSPMessageSerializer msgSerializer = null;
if (this.conf.getBoolean("bsp.checkpoint.enabled", false)) {
msgSerializer = new BSPMessageSerializer(conf,
conf.getInt("bsp.checkpoint.port",
Integer.valueOf(CheckpointRunner.DEFAULT_PORT)));
}
this.messageSerializer = msgSerializer;
initialize();
syncClient.register(taskId.getJobID(), taskId, peerAddress.getHostName(),
peerAddress.getPort());
// initial barrier syncing to get all the hosts to the same point, to get
// consistent peernames.
syncClient.enterBarrier(taskId.getJobID(), taskId, -1);
syncClient.leaveBarrier(taskId.getJobID(), taskId, -1);
setCurrentTaskStatus(new TaskStatus(taskId.getJobID(), taskId, 0,
TaskStatus.State.RUNNING, "running", peerAddress.getHostName(),
TaskStatus.Phase.STARTING));
}
public void initialize() throws Exception {
try {
if (LOG.isDebugEnabled())
LOG.debug("reinitialize(): " + getPeerName());
this.server = RPC.getServer(this, peerAddress.getHostName(),
peerAddress.getPort(), conf);
server.start();
LOG.info(" BSPPeer address:" + peerAddress.getHostName() + " port:"
+ peerAddress.getPort());
} catch (IOException e) {
LOG.error("Fail to start RPC server!", e);
}
syncClient = SyncServiceFactory.getSyncClient(conf);
syncClient.init(conf, taskId.getJobID(), taskId);
}
@Override
public BSPMessage getCurrentMessage() throws IOException {
return localQueue.poll();
}
/*
* (non-Javadoc)
* @see org.apache.hama.bsp.BSPPeerInterface#send(java.net.InetSocketAddress,
* org.apache.hadoop.io.Writable, org.apache.hadoop.io.Writable)
*/
@Override
public void send(String peerName, BSPMessage msg) throws IOException {
LOG.debug("Send bytes (" + msg.getData().toString() + ") to " + peerName);
InetSocketAddress targetPeerAddress = null;
// Get socket for target peer.
if (peerSocketCache.containsKey(peerName)) {
targetPeerAddress = peerSocketCache.get(peerName);
} else {
targetPeerAddress = getAddress(peerName);
peerSocketCache.put(peerName, targetPeerAddress);
}
ConcurrentLinkedQueue<BSPMessage> queue = outgoingQueues
.get(targetPeerAddress);
if (queue == null) {
queue = new ConcurrentLinkedQueue<BSPMessage>();
}
queue.add(msg);
outgoingQueues.put(targetPeerAddress, queue);
}
private String checkpointedPath() {
String backup = conf.get("bsp.checkpoint.prefix_path", "/checkpoint/");
String ckptPath = backup + bspJob.getJobID().toString() + "/"
+ getSuperstepCount() + "/" + this.taskId.toString();
if (LOG.isDebugEnabled())
LOG.debug("Messages are to be saved to " + ckptPath);
return ckptPath;
}
/*
* (non-Javadoc)
* @see org.apache.hama.bsp.BSPPeerInterface#sync()
*/
@Override
public void sync() throws InterruptedException {
try {
enterBarrier();
Iterator<Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>>> it = this.outgoingQueues
.entrySet().iterator();
while (it.hasNext()) {
Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>> entry = it
.next();
BSPPeer peer = getBSPPeerConnection(entry.getKey());
Iterable<BSPMessage> messages = entry.getValue();
BSPMessageBundle bundle = new BSPMessageBundle();
- Combiner combiner = (Combiner) ReflectionUtils.newInstance(
+ if (!conf.getClass("bsp.combiner.class", Combiner.class).equals(Combiner.class)) {
+ Combiner combiner = (Combiner) ReflectionUtils.newInstance(
conf.getClass("bsp.combiner.class", Combiner.class), conf);
- if (combiner != null) {
bundle = combiner.combine(messages);
} else {
for (BSPMessage message : messages) {
bundle.addMessage(message);
}
}
// checkpointing
if (null != this.messageSerializer) {
this.messageSerializer.serialize(new BSPSerializableMessage(
checkpointedPath(), bundle));
}
peer.put(bundle);
}
leaveBarrier();
currentTaskStatus.incrementSuperstepCount();
umbilical.statusUpdate(taskId, currentTaskStatus);
// Clear outgoing queues.
clearOutgoingQueues();
// Add non-processed messages from this iteration for the next's queue.
while (!localQueue.isEmpty()) {
BSPMessage message = localQueue.poll();
localQueueForNextIteration.add(message);
}
// Switch local queues.
localQueue = localQueueForNextIteration;
localQueueForNextIteration = new ConcurrentLinkedQueue<BSPMessage>();
} catch (Exception e) {
LOG.fatal(
"Caught exception during superstep "
+ currentTaskStatus.getSuperstepCount() + "!", e);
// throw new RuntimeException(e);
}
}
protected void enterBarrier() throws Exception {
syncClient.enterBarrier(taskId.getJobID(), taskId,
currentTaskStatus.getSuperstepCount());
}
protected void leaveBarrier() throws Exception {
syncClient.leaveBarrier(taskId.getJobID(), taskId,
currentTaskStatus.getSuperstepCount());
}
public void clear() {
this.localQueue.clear();
this.outgoingQueues.clear();
}
public void close() throws Exception {
this.clear();
syncClient.close();
if (server != null)
server.stop();
if (null != messageSerializer)
this.messageSerializer.close();
}
@Override
public void put(BSPMessage msg) throws IOException {
this.localQueueForNextIteration.add(msg);
}
@Override
public void put(BSPMessageBundle messages) throws IOException {
for (BSPMessage message : messages.getMessages()) {
this.localQueueForNextIteration.add(message);
}
}
@Override
public long getProtocolVersion(String arg0, long arg1) throws IOException {
return BSPPeer.versionID;
}
protected BSPPeer getBSPPeerConnection(InetSocketAddress addr)
throws NullPointerException, IOException {
BSPPeer peer;
peer = peers.get(addr);
if (peer == null) {
synchronized (this.peers) {
peer = (BSPPeer) RPC.getProxy(BSPPeer.class, BSPPeer.versionID, addr,
this.conf);
this.peers.put(addr, peer);
}
}
return peer;
}
/**
* @return the string as host:port of this Peer
*/
public String getPeerName() {
return peerAddress.getHostName() + ":" + peerAddress.getPort();
}
private InetSocketAddress getAddress(String peerName) {
String[] peerAddrParts = peerName.split(":");
if (peerAddrParts.length != 2) {
throw new ArrayIndexOutOfBoundsException(
"Peername must consist of exactly ONE \":\"! Given peername was: "
+ peerName);
}
return new InetSocketAddress(peerAddrParts[0],
Integer.valueOf(peerAddrParts[1]));
}
@Override
public String[] getAllPeerNames() {
initPeerNames();
return allPeers;
}
@Override
public String getPeerName(int index) {
initPeerNames();
return allPeers[index];
}
@Override
public int getNumPeers() {
initPeerNames();
return allPeers.length;
}
private void initPeerNames() {
if (allPeers == null) {
allPeers = syncClient.getAllPeerNames(taskId);
}
}
/**
* @return the number of messages
*/
public int getNumCurrentMessages() {
return localQueue.size();
}
/**
* Sets the current status
*
* @param currentTaskStatus
*/
public void setCurrentTaskStatus(TaskStatus currentTaskStatus) {
this.currentTaskStatus = currentTaskStatus;
}
/**
* @return the count of current super-step
*/
public long getSuperstepCount() {
return currentTaskStatus.getSuperstepCount();
}
/**
* @return the size of local queue
*/
public int getLocalQueueSize() {
return localQueue.size();
}
/**
* @return the size of outgoing queue
*/
public int getOutgoingQueueSize() {
return outgoingQueues.size();
}
/**
* Gets the job configuration.
*
* @return the conf
*/
public Configuration getConfiguration() {
return conf;
}
/**
* Clears local queue
*/
public void clearLocalQueue() {
this.localQueue.clear();
}
/**
* Clears outgoing queues
*/
public void clearOutgoingQueues() {
this.outgoingQueues.clear();
}
}
| false | true | public void sync() throws InterruptedException {
try {
enterBarrier();
Iterator<Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>>> it = this.outgoingQueues
.entrySet().iterator();
while (it.hasNext()) {
Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>> entry = it
.next();
BSPPeer peer = getBSPPeerConnection(entry.getKey());
Iterable<BSPMessage> messages = entry.getValue();
BSPMessageBundle bundle = new BSPMessageBundle();
Combiner combiner = (Combiner) ReflectionUtils.newInstance(
conf.getClass("bsp.combiner.class", Combiner.class), conf);
if (combiner != null) {
bundle = combiner.combine(messages);
} else {
for (BSPMessage message : messages) {
bundle.addMessage(message);
}
}
// checkpointing
if (null != this.messageSerializer) {
this.messageSerializer.serialize(new BSPSerializableMessage(
checkpointedPath(), bundle));
}
peer.put(bundle);
}
leaveBarrier();
currentTaskStatus.incrementSuperstepCount();
umbilical.statusUpdate(taskId, currentTaskStatus);
// Clear outgoing queues.
clearOutgoingQueues();
// Add non-processed messages from this iteration for the next's queue.
while (!localQueue.isEmpty()) {
BSPMessage message = localQueue.poll();
localQueueForNextIteration.add(message);
}
// Switch local queues.
localQueue = localQueueForNextIteration;
localQueueForNextIteration = new ConcurrentLinkedQueue<BSPMessage>();
} catch (Exception e) {
LOG.fatal(
"Caught exception during superstep "
+ currentTaskStatus.getSuperstepCount() + "!", e);
// throw new RuntimeException(e);
}
}
| public void sync() throws InterruptedException {
try {
enterBarrier();
Iterator<Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>>> it = this.outgoingQueues
.entrySet().iterator();
while (it.hasNext()) {
Entry<InetSocketAddress, ConcurrentLinkedQueue<BSPMessage>> entry = it
.next();
BSPPeer peer = getBSPPeerConnection(entry.getKey());
Iterable<BSPMessage> messages = entry.getValue();
BSPMessageBundle bundle = new BSPMessageBundle();
if (!conf.getClass("bsp.combiner.class", Combiner.class).equals(Combiner.class)) {
Combiner combiner = (Combiner) ReflectionUtils.newInstance(
conf.getClass("bsp.combiner.class", Combiner.class), conf);
bundle = combiner.combine(messages);
} else {
for (BSPMessage message : messages) {
bundle.addMessage(message);
}
}
// checkpointing
if (null != this.messageSerializer) {
this.messageSerializer.serialize(new BSPSerializableMessage(
checkpointedPath(), bundle));
}
peer.put(bundle);
}
leaveBarrier();
currentTaskStatus.incrementSuperstepCount();
umbilical.statusUpdate(taskId, currentTaskStatus);
// Clear outgoing queues.
clearOutgoingQueues();
// Add non-processed messages from this iteration for the next's queue.
while (!localQueue.isEmpty()) {
BSPMessage message = localQueue.poll();
localQueueForNextIteration.add(message);
}
// Switch local queues.
localQueue = localQueueForNextIteration;
localQueueForNextIteration = new ConcurrentLinkedQueue<BSPMessage>();
} catch (Exception e) {
LOG.fatal(
"Caught exception during superstep "
+ currentTaskStatus.getSuperstepCount() + "!", e);
// throw new RuntimeException(e);
}
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/sell.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/sell.java
index 71e2d8e..fbf0abd 100644
--- a/src/nl/giantit/minecraft/GiantShop/core/Commands/sell.java
+++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/sell.java
@@ -1,233 +1,233 @@
package nl.giantit.minecraft.GiantShop.core.Commands;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.API.GiantShopAPI;
import nl.giantit.minecraft.GiantShop.API.stock.ItemNotFoundException;
import nl.giantit.minecraft.GiantShop.API.stock.Events.StockUpdateEvent;
import nl.giantit.minecraft.GiantShop.core.config;
import nl.giantit.minecraft.GiantShop.core.perm;
import nl.giantit.minecraft.GiantShop.core.Database.db;
import nl.giantit.minecraft.GiantShop.core.Items.*;
import nl.giantit.minecraft.GiantShop.core.Logger.*;
import nl.giantit.minecraft.GiantShop.core.Tools.InventoryHandler;
import nl.giantit.minecraft.GiantShop.core.Eco.iEco;
import nl.giantit.minecraft.GiantShop.Misc.Heraut;
import nl.giantit.minecraft.GiantShop.Misc.Messages;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Level;
/**
*
* @author Giant
*/
public class sell {
private static config conf = config.Obtain();
private static db DB = db.Obtain();
private static perm perms = perm.Obtain();
private static Messages mH = GiantShop.getPlugin().getMsgHandler();
private static Items iH = GiantShop.getPlugin().getItemHandler();
private static iEco eH = GiantShop.getPlugin().getEcoHandler().getEngine();
public static void sell(Player player, String[] args) {
Heraut.savePlayer(player);
if(perms.has(player, "giantshop.shop.sell")) {
if(args.length >= 2) {
int itemID;
Integer itemType = -1;
int quantity;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType);
if(args.length >= 3) {
try {
quantity = Integer.parseInt(args[2]);
quantity = (quantity > 0) ? quantity : 1;
}catch(NumberFormatException e) {
//Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity"));
Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)");
quantity = 1;
}
}else
quantity = 1;
if(iH.isValidItem(itemID, iT)) {
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, String> where = new HashMap<String, String>();
where.put("itemID", String.valueOf(itemID));
where.put("type", String.valueOf((itemType == null || itemType == 0) ? -1 : itemType));
ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery();
if(resSet.size() == 1) {
HashMap<String, String> res = resSet.get(0);
if(!res.get("buyFor").equals("-1.0")) {
String name = iH.getItemNameByID(itemID, iT);
int perStack = Integer.parseInt(res.get("perStack"));
int stock = Integer.parseInt(res.get("stock"));
int maxStock = Integer.parseInt(res.get("maxStock"));
double buyFor = Double.parseDouble(res.get("buyFor"));
double cost = buyFor * (double) quantity;
int amount = perStack * quantity;
if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || maxStock == -1 || (stock + amount <= maxStock || conf.getBoolean("GiantShop.stock.allowOverStock"))) {
if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) {
double maxInfl = conf.getDouble("GiantShop.stock.maxInflation");
double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation");
int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation");
int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation");
double split = Math.round((atmi + atmd) / 2);
if(maxStock <= atmi + atmd); {
split = maxStock / 2;
atmi = 0;
atmd = maxStock;
}
if(stock >= atmd) {
cost = (buyFor * (1.0 - maxDefl / 100.0)) * (double) quantity;
}else if(stock <= atmi) {
cost = (buyFor * (1.0 + maxInfl / 100.0)) * (double) quantity;
}else{
if(stock < split) {
cost = (double)Math.round(((buyFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0;
}else if(stock > split) {
cost = 2.0 + (double)Math.round(((buyFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0;
}
}
}
ItemStack iStack;
Inventory inv = player.getInventory();
if(itemType != null && itemType != -1) {
if(itemID != 373)
iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount);
else
iStack = new ItemStack(itemID, amount, (short) ((int) itemType));
}else{
iStack = new ItemStack(itemID, amount);
}
int stackAmt = InventoryHandler.hasAmount(inv, iStack);
if(stackAmt >= amount) {
if(conf.getBoolean("GiantShop.global.broadcastSell"))
Heraut.broadcast(player.getName() + " sold some " + name);
eH.deposit(player, cost);
Heraut.say("You have just sold " + amount + " of " + name + " for " + cost);
Heraut.say("Your new balance is: " + eH.getBalance(player));
Logger.Log(LoggerType.SELL,
player,
"{id: " + String.valueOf(itemID) + "; " +
"type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " +
"oS:" + String.valueOf(stock) + "; " +
- "nS:" + String.valueOf(stock + amount) + "; " +
+ "nS:" + String.valueOf((stock != -1 ? stock + amount : stock)) + "; " +
"amount:" + String.valueOf(amount) + ";" +
"total:" + String.valueOf(cost) + ";}");
InventoryHandler.removeItem(inv, iStack);
if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) {
HashMap<String, String> t = new HashMap<String, String>();
t.put("stock", String.valueOf((stock + amount)));
DB.update("#__items").set(t).where(where).updateQuery();
try {
StockUpdateEvent event = new StockUpdateEvent(player, GiantShopAPI.Obtain().getStockAPI().getItemStock(itemID, itemType), StockUpdateEvent.StockUpdateType.INCREASE);
GiantShop.getPlugin().getSrvr().getPluginManager().callEvent(event);
}catch(ItemNotFoundException e) {}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("needed", String.valueOf(amount));
data.put("have", String.valueOf(stackAmt));
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "insufItems", data));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "stockExeedsMaxStock"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noReturns"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
}
| true | true | public static void sell(Player player, String[] args) {
Heraut.savePlayer(player);
if(perms.has(player, "giantshop.shop.sell")) {
if(args.length >= 2) {
int itemID;
Integer itemType = -1;
int quantity;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType);
if(args.length >= 3) {
try {
quantity = Integer.parseInt(args[2]);
quantity = (quantity > 0) ? quantity : 1;
}catch(NumberFormatException e) {
//Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity"));
Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)");
quantity = 1;
}
}else
quantity = 1;
if(iH.isValidItem(itemID, iT)) {
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, String> where = new HashMap<String, String>();
where.put("itemID", String.valueOf(itemID));
where.put("type", String.valueOf((itemType == null || itemType == 0) ? -1 : itemType));
ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery();
if(resSet.size() == 1) {
HashMap<String, String> res = resSet.get(0);
if(!res.get("buyFor").equals("-1.0")) {
String name = iH.getItemNameByID(itemID, iT);
int perStack = Integer.parseInt(res.get("perStack"));
int stock = Integer.parseInt(res.get("stock"));
int maxStock = Integer.parseInt(res.get("maxStock"));
double buyFor = Double.parseDouble(res.get("buyFor"));
double cost = buyFor * (double) quantity;
int amount = perStack * quantity;
if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || maxStock == -1 || (stock + amount <= maxStock || conf.getBoolean("GiantShop.stock.allowOverStock"))) {
if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) {
double maxInfl = conf.getDouble("GiantShop.stock.maxInflation");
double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation");
int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation");
int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation");
double split = Math.round((atmi + atmd) / 2);
if(maxStock <= atmi + atmd); {
split = maxStock / 2;
atmi = 0;
atmd = maxStock;
}
if(stock >= atmd) {
cost = (buyFor * (1.0 - maxDefl / 100.0)) * (double) quantity;
}else if(stock <= atmi) {
cost = (buyFor * (1.0 + maxInfl / 100.0)) * (double) quantity;
}else{
if(stock < split) {
cost = (double)Math.round(((buyFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0;
}else if(stock > split) {
cost = 2.0 + (double)Math.round(((buyFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0;
}
}
}
ItemStack iStack;
Inventory inv = player.getInventory();
if(itemType != null && itemType != -1) {
if(itemID != 373)
iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount);
else
iStack = new ItemStack(itemID, amount, (short) ((int) itemType));
}else{
iStack = new ItemStack(itemID, amount);
}
int stackAmt = InventoryHandler.hasAmount(inv, iStack);
if(stackAmt >= amount) {
if(conf.getBoolean("GiantShop.global.broadcastSell"))
Heraut.broadcast(player.getName() + " sold some " + name);
eH.deposit(player, cost);
Heraut.say("You have just sold " + amount + " of " + name + " for " + cost);
Heraut.say("Your new balance is: " + eH.getBalance(player));
Logger.Log(LoggerType.SELL,
player,
"{id: " + String.valueOf(itemID) + "; " +
"type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " +
"oS:" + String.valueOf(stock) + "; " +
"nS:" + String.valueOf(stock + amount) + "; " +
"amount:" + String.valueOf(amount) + ";" +
"total:" + String.valueOf(cost) + ";}");
InventoryHandler.removeItem(inv, iStack);
if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) {
HashMap<String, String> t = new HashMap<String, String>();
t.put("stock", String.valueOf((stock + amount)));
DB.update("#__items").set(t).where(where).updateQuery();
try {
StockUpdateEvent event = new StockUpdateEvent(player, GiantShopAPI.Obtain().getStockAPI().getItemStock(itemID, itemType), StockUpdateEvent.StockUpdateType.INCREASE);
GiantShop.getPlugin().getSrvr().getPluginManager().callEvent(event);
}catch(ItemNotFoundException e) {}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("needed", String.valueOf(amount));
data.put("have", String.valueOf(stackAmt));
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "insufItems", data));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "stockExeedsMaxStock"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noReturns"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
| public static void sell(Player player, String[] args) {
Heraut.savePlayer(player);
if(perms.has(player, "giantshop.shop.sell")) {
if(args.length >= 2) {
int itemID;
Integer itemType = -1;
int quantity;
if(!args[1].matches("[0-9]+:[0-9]+")) {
try {
itemID = Integer.parseInt(args[1]);
itemType = -1;
}catch(NumberFormatException e) {
ItemID key = iH.getItemIDByName(args[1]);
if(key != null) {
itemID = key.getId();
itemType = key.getType();
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
return;
}
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}else{
try {
String[] data = args[1].split(":");
itemID = Integer.parseInt(data[0]);
itemType = Integer.parseInt(data[1]);
}catch(NumberFormatException e) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
return;
}catch(Exception e) {
if(conf.getBoolean("GiantShop.global.debug") == true) {
GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage());
GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace());
}
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown"));
return;
}
}
Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType);
if(args.length >= 3) {
try {
quantity = Integer.parseInt(args[2]);
quantity = (quantity > 0) ? quantity : 1;
}catch(NumberFormatException e) {
//Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity"));
Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)");
quantity = 1;
}
}else
quantity = 1;
if(iH.isValidItem(itemID, iT)) {
ArrayList<String> fields = new ArrayList<String>();
fields.add("perStack");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, String> where = new HashMap<String, String>();
where.put("itemID", String.valueOf(itemID));
where.put("type", String.valueOf((itemType == null || itemType == 0) ? -1 : itemType));
ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery();
if(resSet.size() == 1) {
HashMap<String, String> res = resSet.get(0);
if(!res.get("buyFor").equals("-1.0")) {
String name = iH.getItemNameByID(itemID, iT);
int perStack = Integer.parseInt(res.get("perStack"));
int stock = Integer.parseInt(res.get("stock"));
int maxStock = Integer.parseInt(res.get("maxStock"));
double buyFor = Double.parseDouble(res.get("buyFor"));
double cost = buyFor * (double) quantity;
int amount = perStack * quantity;
if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || maxStock == -1 || (stock + amount <= maxStock || conf.getBoolean("GiantShop.stock.allowOverStock"))) {
if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) {
double maxInfl = conf.getDouble("GiantShop.stock.maxInflation");
double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation");
int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation");
int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation");
double split = Math.round((atmi + atmd) / 2);
if(maxStock <= atmi + atmd); {
split = maxStock / 2;
atmi = 0;
atmd = maxStock;
}
if(stock >= atmd) {
cost = (buyFor * (1.0 - maxDefl / 100.0)) * (double) quantity;
}else if(stock <= atmi) {
cost = (buyFor * (1.0 + maxInfl / 100.0)) * (double) quantity;
}else{
if(stock < split) {
cost = (double)Math.round(((buyFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0;
}else if(stock > split) {
cost = 2.0 + (double)Math.round(((buyFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0;
}
}
}
ItemStack iStack;
Inventory inv = player.getInventory();
if(itemType != null && itemType != -1) {
if(itemID != 373)
iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount);
else
iStack = new ItemStack(itemID, amount, (short) ((int) itemType));
}else{
iStack = new ItemStack(itemID, amount);
}
int stackAmt = InventoryHandler.hasAmount(inv, iStack);
if(stackAmt >= amount) {
if(conf.getBoolean("GiantShop.global.broadcastSell"))
Heraut.broadcast(player.getName() + " sold some " + name);
eH.deposit(player, cost);
Heraut.say("You have just sold " + amount + " of " + name + " for " + cost);
Heraut.say("Your new balance is: " + eH.getBalance(player));
Logger.Log(LoggerType.SELL,
player,
"{id: " + String.valueOf(itemID) + "; " +
"type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " +
"oS:" + String.valueOf(stock) + "; " +
"nS:" + String.valueOf((stock != -1 ? stock + amount : stock)) + "; " +
"amount:" + String.valueOf(amount) + ";" +
"total:" + String.valueOf(cost) + ";}");
InventoryHandler.removeItem(inv, iStack);
if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) {
HashMap<String, String> t = new HashMap<String, String>();
t.put("stock", String.valueOf((stock + amount)));
DB.update("#__items").set(t).where(where).updateQuery();
try {
StockUpdateEvent event = new StockUpdateEvent(player, GiantShopAPI.Obtain().getStockAPI().getItemStock(itemID, itemType), StockUpdateEvent.StockUpdateType.INCREASE);
GiantShop.getPlugin().getSrvr().getPluginManager().callEvent(event);
}catch(ItemNotFoundException e) {}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("needed", String.valueOf(amount));
data.put("have", String.valueOf(stackAmt));
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "insufItems", data));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "stockExeedsMaxStock"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noReturns"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults"));
}
}else{
Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound"));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "sell");
Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/ContractionRoutingServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/ContractionRoutingServiceImpl.java
index 1e06e264c..aa28cdadf 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/ContractionRoutingServiceImpl.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/ContractionRoutingServiceImpl.java
@@ -1,103 +1,106 @@
/* 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;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.opentripplanner.routing.algorithm.AStar;
import org.opentripplanner.routing.contraction.ContractionHierarchy;
import org.opentripplanner.routing.contraction.ContractionHierarchySet;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseOptions;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.services.RoutingService;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ContractionRoutingServiceImpl implements RoutingService {
private ContractionHierarchySet hierarchies;
@Autowired
public void setHierarchies(ContractionHierarchySet hierarchies) {
this.hierarchies = hierarchies;
}
@Override
public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) {
ContractionHierarchy hierarchy = null;
hierarchy = hierarchies.getHierarchy(options);
if (hierarchy == null) {
Graph _graph = hierarchies.getGraph();
if (options.isArriveBy()) {
ShortestPathTree spt = AStar.getShortestPathTreeBack(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
GraphPath path = spt.getPath(fromVertex);
+ if (path == null) {
+ return null;
+ }
path.reverse();
return path;
} else {
ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
return spt.getPath(toVertex);
}
}
return hierarchy.getShortestPath(fromVertex, toVertex, state, options);
}
@Override
public GraphPath route(Vertex fromVertex, Vertex toVertex, List<Vertex> intermediates, State state, TraverseOptions options) {
Map<Vertex, HashMap<Vertex, GraphPath>> paths = new HashMap<Vertex, HashMap<Vertex,GraphPath>>();
HashMap<Vertex, GraphPath> firstLegPaths = new HashMap<Vertex, GraphPath>();
paths.put(fromVertex, firstLegPaths);
//compute shortest paths between each pair of vertices
for (Vertex v: intermediates) {
HashMap<Vertex, GraphPath> outPaths = new HashMap<Vertex, GraphPath>();
paths.put(v, outPaths);
GraphPath path = route(fromVertex, v, state, options);
firstLegPaths.put (v, path);
for (Vertex tv: intermediates) {
path = route(v, tv, state, options);
outPaths.put (tv, path);
}
path = route(v, toVertex, state, options);
outPaths.put(toVertex, path);
}
//compute shortest path overall
HashSet<Vertex> vertices = new HashSet<Vertex>();
vertices.addAll(intermediates);
GraphPath shortestPath = TSPPathFinder.findShortestPath(toVertex, fromVertex, paths, vertices, state, options);
return shortestPath;
}
}
| true | true | public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) {
ContractionHierarchy hierarchy = null;
hierarchy = hierarchies.getHierarchy(options);
if (hierarchy == null) {
Graph _graph = hierarchies.getGraph();
if (options.isArriveBy()) {
ShortestPathTree spt = AStar.getShortestPathTreeBack(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
GraphPath path = spt.getPath(fromVertex);
path.reverse();
return path;
} else {
ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
return spt.getPath(toVertex);
}
}
return hierarchy.getShortestPath(fromVertex, toVertex, state, options);
}
| public GraphPath route(Vertex fromVertex, Vertex toVertex, State state, TraverseOptions options) {
ContractionHierarchy hierarchy = null;
hierarchy = hierarchies.getHierarchy(options);
if (hierarchy == null) {
Graph _graph = hierarchies.getGraph();
if (options.isArriveBy()) {
ShortestPathTree spt = AStar.getShortestPathTreeBack(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
GraphPath path = spt.getPath(fromVertex);
if (path == null) {
return null;
}
path.reverse();
return path;
} else {
ShortestPathTree spt = AStar.getShortestPathTree(_graph, fromVertex, toVertex, state,
options);
if (spt == null) {
return null;
}
return spt.getPath(toVertex);
}
}
return hierarchy.getShortestPath(fromVertex, toVertex, state, options);
}
|
diff --git a/qcamraw_util/src-plugins/Import_Qcamraw/Import_Qcamraw.java b/qcamraw_util/src-plugins/Import_Qcamraw/Import_Qcamraw.java
index 58fa9db..93400a8 100644
--- a/qcamraw_util/src-plugins/Import_Qcamraw/Import_Qcamraw.java
+++ b/qcamraw_util/src-plugins/Import_Qcamraw/Import_Qcamraw.java
@@ -1,117 +1,114 @@
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;
import ij.plugin.frame.*;
import ij.io.OpenDialog;
import ij.io.FileInfo;
import ij.io.FileOpener;
import java.io.*;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Import_Qcamraw implements PlugIn {
static File dir;
public void run(String arg) {
JFileChooser jc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "qcamraw", "gif");
jc.setFileFilter(filter);
jc.setMultiSelectionEnabled(true);
if (dir==null) {
String sdir = OpenDialog.getDefaultDirectory();
if (sdir!=null)
dir = new File(sdir);
}
if (dir!=null) {
jc.setCurrentDirectory(dir);
}
int returnVal = jc.showOpenDialog(IJ.getInstance());
File[] files = jc.getSelectedFiles();
if (files.length==0) { // getSelectedFiles does not work on some JVMs
files = new File[1];
files[0] = jc.getSelectedFile();
}
String directory = jc.getCurrentDirectory().getPath() + Prefs.getFileSeparator();
ImageCalculator ic = new ImageCalculator();
try{
ImagePlus averagedIm = new ImagePlus();
for (int i = 0; i < files.length; i++) {
- if (files.length > 16) {
- IJ.showMessage("error", "you can average only up to 16 image sets..");
- }
File f = files[i];
HashMap<String, String> headerHash = getHeader(directory, f.getName());
FileInfo fi = loadImages(directory, f.getName(), headerHash);
ImagePlus ip = new FileOpener(fi).open(false);
StackConverter icon = new StackConverter(ip);
icon.convertToGray32();
for (int j = 1; j < 1 + ip.getImageStack().getSize(); j++) { // stack numbering starts with 0!
ip.getImageStack().getProcessor(j).multiply(1.0 / (double) files.length);
}
if (i == 0) {
averagedIm = ip;
} else {
averagedIm = ic.run("Add create 32-bit stack", averagedIm, ip);
}
}
averagedIm.show();
} catch(IOException x){
new ij.gui.MessageDialog(IJ.getInstance(), "errors", "error");
}
}
private HashMap<String, String> getHeader(String directory, String fileName) throws IOException {
HashMap<String, String> headerHash = new HashMap<String, String>();
FileReader fr = new FileReader(directory + fileName);
BufferedReader br = new BufferedReader(fr);
for (int k = 0; k < 8; k++){ // the first 8 lines are critical, according to their documentation.
String headerLine = br.readLine();
String[] keyValue = headerLine.split(": ");
headerHash.put(keyValue[0], keyValue[1]);
}
// it would be better if other key-value pairs are stored.
br.close();
return headerHash;
}
private FileInfo loadImages(String directory, String fileName, HashMap<String, String> headerHash) throws IOException {
String headerSizeValue = (String) headerHash.get("Fixed-Header-Size");
Integer headerSize = Integer.parseInt(headerSizeValue.replaceAll(" \\[bytes\\]",""));
File f = new File(directory + fileName);
long fileLength = f.length();
int frameSize = Integer.parseInt(headerHash.get("Frame-Size").replaceAll(" \\[bytes\\]",""));
String[] roi = headerHash.get("ROI").split(", ");
FileInfo fi = new FileInfo();
fi.width = Integer.parseInt(roi[2]) - Integer.parseInt(roi[0]);
fi.height = Integer.parseInt(roi[3]) - Integer.parseInt(roi[1]);
fi.offset = Integer.parseInt(headerSizeValue.replaceAll(" \\[bytes\\]",""));
fi.nImages = (int) (fileLength - headerSize) / frameSize;
if (headerHash.get("Image-Encoding").matches("raw16")){
fi.fileType = FileInfo.GRAY16_UNSIGNED; // what about other conditions?
}
fi.intelByteOrder = true;
fi.fileName = fileName;
fi.directory = directory;
return fi;
}
}
| true | true | public void run(String arg) {
JFileChooser jc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "qcamraw", "gif");
jc.setFileFilter(filter);
jc.setMultiSelectionEnabled(true);
if (dir==null) {
String sdir = OpenDialog.getDefaultDirectory();
if (sdir!=null)
dir = new File(sdir);
}
if (dir!=null) {
jc.setCurrentDirectory(dir);
}
int returnVal = jc.showOpenDialog(IJ.getInstance());
File[] files = jc.getSelectedFiles();
if (files.length==0) { // getSelectedFiles does not work on some JVMs
files = new File[1];
files[0] = jc.getSelectedFile();
}
String directory = jc.getCurrentDirectory().getPath() + Prefs.getFileSeparator();
ImageCalculator ic = new ImageCalculator();
try{
ImagePlus averagedIm = new ImagePlus();
for (int i = 0; i < files.length; i++) {
if (files.length > 16) {
IJ.showMessage("error", "you can average only up to 16 image sets..");
}
File f = files[i];
HashMap<String, String> headerHash = getHeader(directory, f.getName());
FileInfo fi = loadImages(directory, f.getName(), headerHash);
ImagePlus ip = new FileOpener(fi).open(false);
StackConverter icon = new StackConverter(ip);
icon.convertToGray32();
for (int j = 1; j < 1 + ip.getImageStack().getSize(); j++) { // stack numbering starts with 0!
ip.getImageStack().getProcessor(j).multiply(1.0 / (double) files.length);
}
if (i == 0) {
averagedIm = ip;
} else {
averagedIm = ic.run("Add create 32-bit stack", averagedIm, ip);
}
}
averagedIm.show();
} catch(IOException x){
new ij.gui.MessageDialog(IJ.getInstance(), "errors", "error");
}
}
| public void run(String arg) {
JFileChooser jc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "qcamraw", "gif");
jc.setFileFilter(filter);
jc.setMultiSelectionEnabled(true);
if (dir==null) {
String sdir = OpenDialog.getDefaultDirectory();
if (sdir!=null)
dir = new File(sdir);
}
if (dir!=null) {
jc.setCurrentDirectory(dir);
}
int returnVal = jc.showOpenDialog(IJ.getInstance());
File[] files = jc.getSelectedFiles();
if (files.length==0) { // getSelectedFiles does not work on some JVMs
files = new File[1];
files[0] = jc.getSelectedFile();
}
String directory = jc.getCurrentDirectory().getPath() + Prefs.getFileSeparator();
ImageCalculator ic = new ImageCalculator();
try{
ImagePlus averagedIm = new ImagePlus();
for (int i = 0; i < files.length; i++) {
File f = files[i];
HashMap<String, String> headerHash = getHeader(directory, f.getName());
FileInfo fi = loadImages(directory, f.getName(), headerHash);
ImagePlus ip = new FileOpener(fi).open(false);
StackConverter icon = new StackConverter(ip);
icon.convertToGray32();
for (int j = 1; j < 1 + ip.getImageStack().getSize(); j++) { // stack numbering starts with 0!
ip.getImageStack().getProcessor(j).multiply(1.0 / (double) files.length);
}
if (i == 0) {
averagedIm = ip;
} else {
averagedIm = ic.run("Add create 32-bit stack", averagedIm, ip);
}
}
averagedIm.show();
} catch(IOException x){
new ij.gui.MessageDialog(IJ.getInstance(), "errors", "error");
}
}
|
diff --git a/onebusaway-nyc-transit-data-federation/src/main/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/StifTask.java b/onebusaway-nyc-transit-data-federation/src/main/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/StifTask.java
index 28207860d..e8e188459 100644
--- a/onebusaway-nyc-transit-data-federation/src/main/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/StifTask.java
+++ b/onebusaway-nyc-transit-data-federation/src/main/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/StifTask.java
@@ -1,535 +1,535 @@
/**
* Copyright (c) 2011 Metropolitan Transportation Authority
*
* 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.onebusaway.nyc.transit_data_federation.bundle.tasks.stif;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.GtfsMutableRelationalDao;
import org.onebusaway.nyc.transit_data_federation.bundle.model.NycFederatedTransitDataBundle;
import org.onebusaway.nyc.transit_data_federation.bundle.tasks.stif.model.ServiceCode;
import org.onebusaway.nyc.transit_data_federation.model.nyc.RunData;
import org.onebusaway.utility.ObjectSerializationLibrary;
import org.opentripplanner.common.model.P2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Load STIF data, including the mapping between destination sign codes and trip
* ids, into the database
*
* @author bdferris
*
*/
public class StifTask implements Runnable {
private Logger _log = LoggerFactory.getLogger(StifTask.class);
private GtfsMutableRelationalDao _gtfsMutableRelationalDao;
private List<File> _stifPaths = new ArrayList<File>();
private Set<String> _notInServiceDscs = new HashSet<String>();
private File _notInServiceDscPath;
@Autowired
private NycFederatedTransitDataBundle _bundle;
private String logPath;
private boolean fallBackToStifBlocks = false;
private MultiCSVLogger csvLogger;
private HashMap<String, Set<AgencyAndId>> routeIdsByDsc = new HashMap<String, Set<AgencyAndId>>();
@Autowired
public void setGtfsMutableRelationalDao(
GtfsMutableRelationalDao gtfsMutableRelationalDao) {
_gtfsMutableRelationalDao = gtfsMutableRelationalDao;
}
/**
* The path of the directory containing STIF files to process
*/
public void setStifPath(File path) {
_stifPaths.add(path);
}
public void setStifPaths(List<File> paths) {
_stifPaths.addAll(paths);
}
public void setNotInServiceDsc(String notInServiceDsc) {
_notInServiceDscs.add(notInServiceDsc);
}
public void setNotInServiceDscs(List<String> notInServiceDscs) {
_notInServiceDscs.addAll(notInServiceDscs);
}
public void setNotInServiceDscPath(File notInServiceDscPath) {
_notInServiceDscPath = notInServiceDscPath;
}
public void setLogPath(String logPath) {
this.logPath = logPath;
}
public void run() {
csvLogger = new MultiCSVLogger(logPath);
StifTripLoader loader = new StifTripLoader();
loader.setGtfsDao(_gtfsMutableRelationalDao);
loader.setLogger(csvLogger);
for (File path : _stifPaths) {
loadStif(path, loader);
}
computeBlocksFromRuns(loader);
warnOnMissingTrips();
if (fallBackToStifBlocks) {
loadStifBlocks(loader);
}
Map<AgencyAndId, RunData> runsForTrip = loader.getRunsForTrip();
//store trip-run mapping in bundle
try {
ObjectSerializationLibrary.writeObject(_bundle.getTripRunDataPath(),
runsForTrip);
} catch (IOException e) {
throw new IllegalStateException(e);
}
Map<String, List<AgencyAndId>> dscToTripMap = loader.getTripMapping();
Map<AgencyAndId, String> tripToDscMap = new HashMap<AgencyAndId, String>();
Set<String> inServiceDscs = new HashSet<String>();
logDSCStatistics(dscToTripMap, tripToDscMap);
int withoutMatch = loader.getTripsWithoutMatchCount();
int total = loader.getTripsCount();
_log.info("stif trips without match: " + withoutMatch + " / " + total);
readNotInServiceDscs();
serializeDSCData(dscToTripMap, tripToDscMap, inServiceDscs);
csvLogger.summarize();
csvLogger = null; //ensure no writes after summary
}
private void logDSCStatistics(Map<String, List<AgencyAndId>> dscToTripMap,
Map<AgencyAndId, String> tripToDscMap) {
csvLogger.header("dsc_statistics.csv", "dsc,number_of_trips_in_stif,number_of_distinct_route_ids_in_gtfs");
for (Map.Entry<String, List<AgencyAndId>> entry : dscToTripMap.entrySet()) {
String destinationSignCode = entry.getKey();
List<AgencyAndId> tripIds = entry.getValue();
for (AgencyAndId tripId : tripIds) {
tripToDscMap.put(tripId, destinationSignCode);
}
Set<AgencyAndId> routeIds = routeIdsByDsc.get(destinationSignCode);
if (routeIds != null) {
csvLogger.log("dsc_statistics.csv", destinationSignCode, tripIds.size(), routeIds.size());
} else {
csvLogger.log("dsc_statistics.csv", destinationSignCode, tripIds.size(), 0);
}
}
}
private void serializeDSCData(Map<String, List<AgencyAndId>> dscToTripMap,
Map<AgencyAndId, String> tripToDscMap, Set<String> inServiceDscs) {
for (String notInServiceDsc : _notInServiceDscs) {
if (inServiceDscs.contains(notInServiceDsc))
_log.warn("overlap between in-service and not-in-service dscs: "
+ notInServiceDsc);
// clear out trip mappings for out of service DSCs
dscToTripMap.put(notInServiceDsc, new ArrayList<AgencyAndId>());
}
try {
ObjectSerializationLibrary.writeObject(_bundle.getNotInServiceDSCs(),
_notInServiceDscs);
ObjectSerializationLibrary.writeObject(_bundle.getTripsForDSCIndex(),
tripToDscMap);
ObjectSerializationLibrary.writeObject(_bundle.getDSCForTripIndex(),
dscToTripMap);
} catch (IOException e) {
throw new IllegalStateException("error serializing DSC/STIF data", e);
}
}
private void loadStifBlocks(StifTripLoader loader) {
Map<Trip, RawRunData> rawData = loader.getRawRunDataByTrip();
for (Map.Entry<Trip, RawRunData> entry : rawData.entrySet()) {
Trip trip = entry.getKey();
if (trip.getBlockId() == null || trip.getBlockId().length() == 0) {
RawRunData data = entry.getValue();
trip.setBlockId(trip.getServiceId().getId() + "_STIF_" + data.getDepotCode() + "_" + data.getBlock());
_gtfsMutableRelationalDao.updateEntity(trip);
}
}
}
class TripWithStartTime implements Comparable<TripWithStartTime> {
private int startTime;
private Trip trip;
public TripWithStartTime(Trip trip) {
this.trip = trip;
List<StopTime> stopTimes = _gtfsMutableRelationalDao.getStopTimesForTrip(trip);
startTime = stopTimes.get(0).getDepartureTime();
}
// this is just for creating bogus objects for searching
public TripWithStartTime(int startTime) {
this.startTime = startTime;
}
@Override
public int compareTo(TripWithStartTime o) {
return startTime - o.startTime;
}
public String toString() {
return "TripWithStartTime(" + startTime + ", " + trip + ")";
}
}
@SuppressWarnings("rawtypes")
class RawTripComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Integer) {
if (o2 instanceof Integer) {
return ((Integer) o1) - ((Integer) o2);
} else {
RawTrip trip = (RawTrip) o2;
return ((Integer) o1) - trip.listedFirstStopTime;
}
} else {
if (o2 instanceof Integer) {
return ((RawTrip) o1).listedFirstStopTime - ((Integer) o2);
} else {
RawTrip trip = (RawTrip) o2;
return ((RawTrip) o1).listedFirstStopTime - trip.listedFirstStopTime;
}
}
}
}
private void computeBlocksFromRuns(StifTripLoader loader) {
int blockNo = 0;
HashSet<Trip> usedGtfsTrips = new HashSet<Trip>();
csvLogger.header("non_pullin_without_next_movement.csv", "stif_trip,stif_filename,stif_trip_record_line_num");
csvLogger.header(
"stif_trips_without_pullout.csv",
"stif_trip,stif_filename,stif_trip_record_line_num,gtfs_trip_id,synthesized_block_id");
csvLogger.header("matched_trips_gtfs_stif.csv", "agency_id,gtfs_service_id,service_id,blockId,tripId,dsc,firstStop,"+
"firstStopTime,lastStop,lastStopTime,runId,reliefRunId,recoveryTime,firstInSeq,lastInSeq,signCodeRoute,routeId");
Map<ServiceCode, List<RawTrip>> rawData = loader.getRawStifData();
for (Map.Entry<ServiceCode, List<RawTrip>> entry : rawData.entrySet()) {
List<RawTrip> rawTrips = entry.getValue();
// this is a monster -- we want to group these by run and find the
// pullouts
HashMap<String, List<RawTrip>> tripsByRun = new HashMap<String, List<RawTrip>>();
HashSet<RawTrip> unmatchedTrips = new HashSet<RawTrip>();
ArrayList<RawTrip> pullouts = new ArrayList<RawTrip>();
for (RawTrip trip : rawTrips) {
String runId = trip.getRunIdWithDepot();
List<RawTrip> byRun = tripsByRun.get(runId);
if (byRun == null) {
byRun = new ArrayList<RawTrip>();
tripsByRun.put(runId, byRun);
}
unmatchedTrips.add(trip);
byRun.add(trip);
if (trip.type == StifTripType.PULLOUT) {
pullouts.add(trip);
}
if (trip.type == StifTripType.DEADHEAD &&
trip.listedFirstStopTime == trip.listedLastStopTime + trip.recoveryTime) {
_log.warn("Zero-length deadhead. If this immediately follows a pullout, "
+ "tracing might fail. If it does, we will mark some trips as trips "
+ "without pullout.");
}
}
for (List<RawTrip> byRun : tripsByRun.values()) {
Collections.sort(byRun);
}
for (RawTrip pullout : pullouts) {
blockNo ++;
RawTrip lastTrip = pullout;
int i = 0;
HashSet<P2<String>> blockIds = new HashSet<P2<String>>();
while (lastTrip.type != StifTripType.PULLIN) {
unmatchedTrips.remove(lastTrip);
if (++i > 200) {
_log.warn("We seem to be caught in an infinite loop; this is usually caused\n"
+ "by two trips on the same run having the same start time. Since nobody\n"
+ "can be in two places at once, this is an error in the STIF. Some trips\n"
+ "will end up with missing blocks and the log will be screwed up. A \n"
+ "representative trip starts at "
+ lastTrip.firstStop
+ " at " + lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
String nextRunId = lastTrip.getNextRunIdWithDepot();
if (nextRunId == null) {
csvLogger.log("non_pullin_without_next_movement.csv", lastTrip.id, lastTrip.path, lastTrip.lineNumber);
_log.warn("A non-pullin has no next run; some trips will end up with missing blocks"
+ " and the log will be messed up. The bad trip starts at " + lastTrip.firstStop + " at "
+ lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
List<RawTrip> trips = tripsByRun.get(nextRunId);
if (trips == null) {
_log.warn("No trips for run " + nextRunId);
break;
}
int nextTripStartTime = lastTrip.listedLastStopTime + lastTrip.recoveryTime * 60;
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(trips, nextTripStartTime, new RawTripComparator());
if (index < 0) {
index = -(index + 1);
}
if (index >= trips.size()) {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, but there are no trips after "
+ lastTrip.firstStopTime
+ ", so some trips will end up with missing blocks.");
break;
}
RawTrip trip = trips.get(index);
if (trip == lastTrip) {
//we have two trips with the same start time -- usually one is a pullout of zero-length
//we don't know if we got the first one or the last one, since Collections.binarySearch
//makes no guarantees
if (index > 0 && trips.get(index-1).listedFirstStopTime == nextTripStartTime) {
index --;
trip = trips.get(index);
} else if (index < trips.size() - 1 && trips.get(index+1).listedFirstStopTime == nextTripStartTime) {
index ++;
} else {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, and that the next trip should start at " + nextTripStartTime
+ ". As it happens, *this* trip starts at that time, but no other trips on"
+ " this run do, so some trips will end up with missing blocks.");
break;
}
}
lastTrip = trip;
for (Trip gtfsTrip : lastTrip.getGtfsTrips()) {
RawRunData rawRunData = loader.getRawRunDataByTrip().get(gtfsTrip);
String blockId;
if (trip.agencyId.equals("MTA NYCT")) {
blockId = gtfsTrip.getServiceId().getId() + "_" + rawRunData.getDepotCode() + "_" + pullout.firstStopTime + "_" + pullout.getRunIdWithDepot() + "_" + blockNo;
} else {
blockId = gtfsTrip.getServiceId().getId() + "_" + trip.blockId + "_" + blockNo;
}
blockId = blockId.intern();
blockIds.add(new P2<String>(blockId, gtfsTrip.getServiceId().getId()));
gtfsTrip.setBlockId(blockId);
_gtfsMutableRelationalDao.updateEntity(gtfsTrip);
AgencyAndId routeId = gtfsTrip.getRoute().getId();
addToMapSet(routeIdsByDsc, trip.getDsc(), routeId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
gtfsTrip.getId().getId(), blockId, routeId.getId());
usedGtfsTrips.add(gtfsTrip);
}
if (lastTrip.type == StifTripType.DEADHEAD) {
for (P2<String> blockId : blockIds) {
String tripId = String.format("deadhead_%s_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.lastStop, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), tripId, blockId.getFirst(), "no gtfs trip");
}
}
}
unmatchedTrips.remove(lastTrip);
for (P2<String> blockId : blockIds) {
String pulloutTripId = String.format("pullout_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.runId);
dumpBlockDataForTrip(pullout, blockId.getSecond(), pulloutTripId , blockId.getFirst(), "no gtfs trip");
String pullinTripId = String.format("pullin_%s_%s_%s_%s", blockId.getSecond(), lastTrip.lastStop, lastTrip.lastStopTime, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), pullinTripId, blockId.getFirst(), "no gtfs trip");
}
}
for (RawTrip trip : unmatchedTrips) {
_log.warn("STIF trip: " + trip + " on schedule " + entry.getKey()
+ " trip type " + trip.type
+ " must not have an associated pullout");
for (Trip gtfsTrip : trip.getGtfsTrips()) {
blockNo++;
String blockId = gtfsTrip.getServiceId().getId() + "_" + trip.firstStop + "_"
+ trip.firstStopTime + "_" + trip.runId.replace("-", "_")
+ "_orphan_" + blockNo;
_log.warn("Generating single-trip block id for GTFS trip: "
+ gtfsTrip.getId() + " : " + blockId);
gtfsTrip.setBlockId(blockId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
- gtfsTrip.getId().getId(), blockId, gtfsTrip.getBlockId());
+ gtfsTrip.getId().getId(), blockId, gtfsTrip.getRoute().getId().getId());
csvLogger.log("stif_trips_without_pullout.csv", trip.id, trip.path,
trip.lineNumber, gtfsTrip.getId(), blockId);
usedGtfsTrips.add(gtfsTrip);
}
}
}
HashSet<Route> routesWithTrips = new HashSet<Route>();
csvLogger.header("gtfs_trips_with_no_stif_match.csv", "gtfs_trip_id,stif_trip");
Collection<Trip> allTrips = _gtfsMutableRelationalDao.getAllTrips();
for (Trip trip : allTrips) {
if (usedGtfsTrips.contains(trip)) {
routesWithTrips.add(trip.getRoute());
} else {
csvLogger.log("gtfs_trips_with_no_stif_match.csv", trip.getId(), loader.getSupport().getTripAsIdentifier(trip));
}
}
csvLogger.header("route_ids_with_no_trips.csv", "agency_id,route_id");
for (Route route : _gtfsMutableRelationalDao.getAllRoutes()) {
if (routesWithTrips.contains(route)) {
continue;
}
csvLogger.log("route_ids_with_no_trips.csv", route.getId().getAgencyId(), route.getId().getId());
}
}
/**
* An extremely common pattern: add an item to a set in a hash value, creating that set if
* necessary; based on code from OTP with permission of copyright holder (OpenPlans).
*/
public static final <T, U> void addToMapSet(Map<T, Set<U>> mapList, T key, U value) {
Set<U> list = mapList.get(key);
if (list == null) {
list = new HashSet<U>();
mapList.put(key, list);
}
list.add(value);
}
/**
* Dump some raw block matching data to a CSV file from stif trips
*/
private void dumpBlockDataForTrip(RawTrip trip, String gtfsServiceId,
String tripId, String blockId, String routeId) {
csvLogger.log("matched_trips_gtfs_stif.csv", trip.agencyId,
gtfsServiceId, trip.serviceCode, blockId, tripId, trip.getDsc(), trip.firstStop,
trip.firstStopTime, trip.lastStop, trip.lastStopTime, trip.runId,
trip.reliefRunId, trip.recoveryTime, trip.firstTripInSequence,
trip.lastTripInSequence, trip.getSignCodeRoute(), routeId);
}
private void warnOnMissingTrips() {
for (Trip t : _gtfsMutableRelationalDao.getAllTrips()) {
String blockId = t.getBlockId();
if (blockId == null || blockId.equals("")) {
_log.warn("When matching GTFS to STIF, failed to find block in STIF for "
+ t.getId());
}
}
}
public void loadStif(File path, StifTripLoader loader) {
// Exclude files and directories like .svn
if (path.getName().startsWith("."))
return;
if (path.isDirectory()) {
for (String filename : path.list()) {
File contained = new File(path, filename);
loadStif(contained, loader);
}
} else {
loader.run(path);
}
}
private void readNotInServiceDscs() {
if (_notInServiceDscPath != null) {
try {
BufferedReader reader = new BufferedReader(new FileReader(
_notInServiceDscPath));
String line = null;
while ((line = reader.readLine()) != null)
_notInServiceDscs.add(line);
} catch (IOException ex) {
throw new IllegalStateException("unable to read nonInServiceDscPath: "
+ _notInServiceDscPath);
}
}
}
/**
* Whether blocks should come be computed from runs (true) or read from the STIF (false)
* @return
*/
public boolean usesFallBackToStifBlocks() {
return fallBackToStifBlocks;
}
public void setFallBackToStifBlocks(boolean fallBackToStifBlocks) {
this.fallBackToStifBlocks = fallBackToStifBlocks;
}
}
| true | true | private void computeBlocksFromRuns(StifTripLoader loader) {
int blockNo = 0;
HashSet<Trip> usedGtfsTrips = new HashSet<Trip>();
csvLogger.header("non_pullin_without_next_movement.csv", "stif_trip,stif_filename,stif_trip_record_line_num");
csvLogger.header(
"stif_trips_without_pullout.csv",
"stif_trip,stif_filename,stif_trip_record_line_num,gtfs_trip_id,synthesized_block_id");
csvLogger.header("matched_trips_gtfs_stif.csv", "agency_id,gtfs_service_id,service_id,blockId,tripId,dsc,firstStop,"+
"firstStopTime,lastStop,lastStopTime,runId,reliefRunId,recoveryTime,firstInSeq,lastInSeq,signCodeRoute,routeId");
Map<ServiceCode, List<RawTrip>> rawData = loader.getRawStifData();
for (Map.Entry<ServiceCode, List<RawTrip>> entry : rawData.entrySet()) {
List<RawTrip> rawTrips = entry.getValue();
// this is a monster -- we want to group these by run and find the
// pullouts
HashMap<String, List<RawTrip>> tripsByRun = new HashMap<String, List<RawTrip>>();
HashSet<RawTrip> unmatchedTrips = new HashSet<RawTrip>();
ArrayList<RawTrip> pullouts = new ArrayList<RawTrip>();
for (RawTrip trip : rawTrips) {
String runId = trip.getRunIdWithDepot();
List<RawTrip> byRun = tripsByRun.get(runId);
if (byRun == null) {
byRun = new ArrayList<RawTrip>();
tripsByRun.put(runId, byRun);
}
unmatchedTrips.add(trip);
byRun.add(trip);
if (trip.type == StifTripType.PULLOUT) {
pullouts.add(trip);
}
if (trip.type == StifTripType.DEADHEAD &&
trip.listedFirstStopTime == trip.listedLastStopTime + trip.recoveryTime) {
_log.warn("Zero-length deadhead. If this immediately follows a pullout, "
+ "tracing might fail. If it does, we will mark some trips as trips "
+ "without pullout.");
}
}
for (List<RawTrip> byRun : tripsByRun.values()) {
Collections.sort(byRun);
}
for (RawTrip pullout : pullouts) {
blockNo ++;
RawTrip lastTrip = pullout;
int i = 0;
HashSet<P2<String>> blockIds = new HashSet<P2<String>>();
while (lastTrip.type != StifTripType.PULLIN) {
unmatchedTrips.remove(lastTrip);
if (++i > 200) {
_log.warn("We seem to be caught in an infinite loop; this is usually caused\n"
+ "by two trips on the same run having the same start time. Since nobody\n"
+ "can be in two places at once, this is an error in the STIF. Some trips\n"
+ "will end up with missing blocks and the log will be screwed up. A \n"
+ "representative trip starts at "
+ lastTrip.firstStop
+ " at " + lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
String nextRunId = lastTrip.getNextRunIdWithDepot();
if (nextRunId == null) {
csvLogger.log("non_pullin_without_next_movement.csv", lastTrip.id, lastTrip.path, lastTrip.lineNumber);
_log.warn("A non-pullin has no next run; some trips will end up with missing blocks"
+ " and the log will be messed up. The bad trip starts at " + lastTrip.firstStop + " at "
+ lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
List<RawTrip> trips = tripsByRun.get(nextRunId);
if (trips == null) {
_log.warn("No trips for run " + nextRunId);
break;
}
int nextTripStartTime = lastTrip.listedLastStopTime + lastTrip.recoveryTime * 60;
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(trips, nextTripStartTime, new RawTripComparator());
if (index < 0) {
index = -(index + 1);
}
if (index >= trips.size()) {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, but there are no trips after "
+ lastTrip.firstStopTime
+ ", so some trips will end up with missing blocks.");
break;
}
RawTrip trip = trips.get(index);
if (trip == lastTrip) {
//we have two trips with the same start time -- usually one is a pullout of zero-length
//we don't know if we got the first one or the last one, since Collections.binarySearch
//makes no guarantees
if (index > 0 && trips.get(index-1).listedFirstStopTime == nextTripStartTime) {
index --;
trip = trips.get(index);
} else if (index < trips.size() - 1 && trips.get(index+1).listedFirstStopTime == nextTripStartTime) {
index ++;
} else {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, and that the next trip should start at " + nextTripStartTime
+ ". As it happens, *this* trip starts at that time, but no other trips on"
+ " this run do, so some trips will end up with missing blocks.");
break;
}
}
lastTrip = trip;
for (Trip gtfsTrip : lastTrip.getGtfsTrips()) {
RawRunData rawRunData = loader.getRawRunDataByTrip().get(gtfsTrip);
String blockId;
if (trip.agencyId.equals("MTA NYCT")) {
blockId = gtfsTrip.getServiceId().getId() + "_" + rawRunData.getDepotCode() + "_" + pullout.firstStopTime + "_" + pullout.getRunIdWithDepot() + "_" + blockNo;
} else {
blockId = gtfsTrip.getServiceId().getId() + "_" + trip.blockId + "_" + blockNo;
}
blockId = blockId.intern();
blockIds.add(new P2<String>(blockId, gtfsTrip.getServiceId().getId()));
gtfsTrip.setBlockId(blockId);
_gtfsMutableRelationalDao.updateEntity(gtfsTrip);
AgencyAndId routeId = gtfsTrip.getRoute().getId();
addToMapSet(routeIdsByDsc, trip.getDsc(), routeId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
gtfsTrip.getId().getId(), blockId, routeId.getId());
usedGtfsTrips.add(gtfsTrip);
}
if (lastTrip.type == StifTripType.DEADHEAD) {
for (P2<String> blockId : blockIds) {
String tripId = String.format("deadhead_%s_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.lastStop, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), tripId, blockId.getFirst(), "no gtfs trip");
}
}
}
unmatchedTrips.remove(lastTrip);
for (P2<String> blockId : blockIds) {
String pulloutTripId = String.format("pullout_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.runId);
dumpBlockDataForTrip(pullout, blockId.getSecond(), pulloutTripId , blockId.getFirst(), "no gtfs trip");
String pullinTripId = String.format("pullin_%s_%s_%s_%s", blockId.getSecond(), lastTrip.lastStop, lastTrip.lastStopTime, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), pullinTripId, blockId.getFirst(), "no gtfs trip");
}
}
for (RawTrip trip : unmatchedTrips) {
_log.warn("STIF trip: " + trip + " on schedule " + entry.getKey()
+ " trip type " + trip.type
+ " must not have an associated pullout");
for (Trip gtfsTrip : trip.getGtfsTrips()) {
blockNo++;
String blockId = gtfsTrip.getServiceId().getId() + "_" + trip.firstStop + "_"
+ trip.firstStopTime + "_" + trip.runId.replace("-", "_")
+ "_orphan_" + blockNo;
_log.warn("Generating single-trip block id for GTFS trip: "
+ gtfsTrip.getId() + " : " + blockId);
gtfsTrip.setBlockId(blockId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
gtfsTrip.getId().getId(), blockId, gtfsTrip.getBlockId());
csvLogger.log("stif_trips_without_pullout.csv", trip.id, trip.path,
trip.lineNumber, gtfsTrip.getId(), blockId);
usedGtfsTrips.add(gtfsTrip);
}
}
}
HashSet<Route> routesWithTrips = new HashSet<Route>();
csvLogger.header("gtfs_trips_with_no_stif_match.csv", "gtfs_trip_id,stif_trip");
Collection<Trip> allTrips = _gtfsMutableRelationalDao.getAllTrips();
for (Trip trip : allTrips) {
if (usedGtfsTrips.contains(trip)) {
routesWithTrips.add(trip.getRoute());
} else {
csvLogger.log("gtfs_trips_with_no_stif_match.csv", trip.getId(), loader.getSupport().getTripAsIdentifier(trip));
}
}
csvLogger.header("route_ids_with_no_trips.csv", "agency_id,route_id");
for (Route route : _gtfsMutableRelationalDao.getAllRoutes()) {
if (routesWithTrips.contains(route)) {
continue;
}
csvLogger.log("route_ids_with_no_trips.csv", route.getId().getAgencyId(), route.getId().getId());
}
}
| private void computeBlocksFromRuns(StifTripLoader loader) {
int blockNo = 0;
HashSet<Trip> usedGtfsTrips = new HashSet<Trip>();
csvLogger.header("non_pullin_without_next_movement.csv", "stif_trip,stif_filename,stif_trip_record_line_num");
csvLogger.header(
"stif_trips_without_pullout.csv",
"stif_trip,stif_filename,stif_trip_record_line_num,gtfs_trip_id,synthesized_block_id");
csvLogger.header("matched_trips_gtfs_stif.csv", "agency_id,gtfs_service_id,service_id,blockId,tripId,dsc,firstStop,"+
"firstStopTime,lastStop,lastStopTime,runId,reliefRunId,recoveryTime,firstInSeq,lastInSeq,signCodeRoute,routeId");
Map<ServiceCode, List<RawTrip>> rawData = loader.getRawStifData();
for (Map.Entry<ServiceCode, List<RawTrip>> entry : rawData.entrySet()) {
List<RawTrip> rawTrips = entry.getValue();
// this is a monster -- we want to group these by run and find the
// pullouts
HashMap<String, List<RawTrip>> tripsByRun = new HashMap<String, List<RawTrip>>();
HashSet<RawTrip> unmatchedTrips = new HashSet<RawTrip>();
ArrayList<RawTrip> pullouts = new ArrayList<RawTrip>();
for (RawTrip trip : rawTrips) {
String runId = trip.getRunIdWithDepot();
List<RawTrip> byRun = tripsByRun.get(runId);
if (byRun == null) {
byRun = new ArrayList<RawTrip>();
tripsByRun.put(runId, byRun);
}
unmatchedTrips.add(trip);
byRun.add(trip);
if (trip.type == StifTripType.PULLOUT) {
pullouts.add(trip);
}
if (trip.type == StifTripType.DEADHEAD &&
trip.listedFirstStopTime == trip.listedLastStopTime + trip.recoveryTime) {
_log.warn("Zero-length deadhead. If this immediately follows a pullout, "
+ "tracing might fail. If it does, we will mark some trips as trips "
+ "without pullout.");
}
}
for (List<RawTrip> byRun : tripsByRun.values()) {
Collections.sort(byRun);
}
for (RawTrip pullout : pullouts) {
blockNo ++;
RawTrip lastTrip = pullout;
int i = 0;
HashSet<P2<String>> blockIds = new HashSet<P2<String>>();
while (lastTrip.type != StifTripType.PULLIN) {
unmatchedTrips.remove(lastTrip);
if (++i > 200) {
_log.warn("We seem to be caught in an infinite loop; this is usually caused\n"
+ "by two trips on the same run having the same start time. Since nobody\n"
+ "can be in two places at once, this is an error in the STIF. Some trips\n"
+ "will end up with missing blocks and the log will be screwed up. A \n"
+ "representative trip starts at "
+ lastTrip.firstStop
+ " at " + lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
String nextRunId = lastTrip.getNextRunIdWithDepot();
if (nextRunId == null) {
csvLogger.log("non_pullin_without_next_movement.csv", lastTrip.id, lastTrip.path, lastTrip.lineNumber);
_log.warn("A non-pullin has no next run; some trips will end up with missing blocks"
+ " and the log will be messed up. The bad trip starts at " + lastTrip.firstStop + " at "
+ lastTrip.firstStopTime + " on " + lastTrip.getRunIdWithDepot() + " on " + lastTrip.serviceCode);
break;
}
List<RawTrip> trips = tripsByRun.get(nextRunId);
if (trips == null) {
_log.warn("No trips for run " + nextRunId);
break;
}
int nextTripStartTime = lastTrip.listedLastStopTime + lastTrip.recoveryTime * 60;
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(trips, nextTripStartTime, new RawTripComparator());
if (index < 0) {
index = -(index + 1);
}
if (index >= trips.size()) {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, but there are no trips after "
+ lastTrip.firstStopTime
+ ", so some trips will end up with missing blocks.");
break;
}
RawTrip trip = trips.get(index);
if (trip == lastTrip) {
//we have two trips with the same start time -- usually one is a pullout of zero-length
//we don't know if we got the first one or the last one, since Collections.binarySearch
//makes no guarantees
if (index > 0 && trips.get(index-1).listedFirstStopTime == nextTripStartTime) {
index --;
trip = trips.get(index);
} else if (index < trips.size() - 1 && trips.get(index+1).listedFirstStopTime == nextTripStartTime) {
index ++;
} else {
_log.warn("The preceding trip says that the run "
+ nextRunId
+ " is next, and that the next trip should start at " + nextTripStartTime
+ ". As it happens, *this* trip starts at that time, but no other trips on"
+ " this run do, so some trips will end up with missing blocks.");
break;
}
}
lastTrip = trip;
for (Trip gtfsTrip : lastTrip.getGtfsTrips()) {
RawRunData rawRunData = loader.getRawRunDataByTrip().get(gtfsTrip);
String blockId;
if (trip.agencyId.equals("MTA NYCT")) {
blockId = gtfsTrip.getServiceId().getId() + "_" + rawRunData.getDepotCode() + "_" + pullout.firstStopTime + "_" + pullout.getRunIdWithDepot() + "_" + blockNo;
} else {
blockId = gtfsTrip.getServiceId().getId() + "_" + trip.blockId + "_" + blockNo;
}
blockId = blockId.intern();
blockIds.add(new P2<String>(blockId, gtfsTrip.getServiceId().getId()));
gtfsTrip.setBlockId(blockId);
_gtfsMutableRelationalDao.updateEntity(gtfsTrip);
AgencyAndId routeId = gtfsTrip.getRoute().getId();
addToMapSet(routeIdsByDsc, trip.getDsc(), routeId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
gtfsTrip.getId().getId(), blockId, routeId.getId());
usedGtfsTrips.add(gtfsTrip);
}
if (lastTrip.type == StifTripType.DEADHEAD) {
for (P2<String> blockId : blockIds) {
String tripId = String.format("deadhead_%s_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.lastStop, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), tripId, blockId.getFirst(), "no gtfs trip");
}
}
}
unmatchedTrips.remove(lastTrip);
for (P2<String> blockId : blockIds) {
String pulloutTripId = String.format("pullout_%s_%s_%s_%s", blockId.getSecond(), lastTrip.firstStop, lastTrip.firstStopTime, lastTrip.runId);
dumpBlockDataForTrip(pullout, blockId.getSecond(), pulloutTripId , blockId.getFirst(), "no gtfs trip");
String pullinTripId = String.format("pullin_%s_%s_%s_%s", blockId.getSecond(), lastTrip.lastStop, lastTrip.lastStopTime, lastTrip.runId);
dumpBlockDataForTrip(lastTrip, blockId.getSecond(), pullinTripId, blockId.getFirst(), "no gtfs trip");
}
}
for (RawTrip trip : unmatchedTrips) {
_log.warn("STIF trip: " + trip + " on schedule " + entry.getKey()
+ " trip type " + trip.type
+ " must not have an associated pullout");
for (Trip gtfsTrip : trip.getGtfsTrips()) {
blockNo++;
String blockId = gtfsTrip.getServiceId().getId() + "_" + trip.firstStop + "_"
+ trip.firstStopTime + "_" + trip.runId.replace("-", "_")
+ "_orphan_" + blockNo;
_log.warn("Generating single-trip block id for GTFS trip: "
+ gtfsTrip.getId() + " : " + blockId);
gtfsTrip.setBlockId(blockId);
dumpBlockDataForTrip(trip, gtfsTrip.getServiceId().getId(),
gtfsTrip.getId().getId(), blockId, gtfsTrip.getRoute().getId().getId());
csvLogger.log("stif_trips_without_pullout.csv", trip.id, trip.path,
trip.lineNumber, gtfsTrip.getId(), blockId);
usedGtfsTrips.add(gtfsTrip);
}
}
}
HashSet<Route> routesWithTrips = new HashSet<Route>();
csvLogger.header("gtfs_trips_with_no_stif_match.csv", "gtfs_trip_id,stif_trip");
Collection<Trip> allTrips = _gtfsMutableRelationalDao.getAllTrips();
for (Trip trip : allTrips) {
if (usedGtfsTrips.contains(trip)) {
routesWithTrips.add(trip.getRoute());
} else {
csvLogger.log("gtfs_trips_with_no_stif_match.csv", trip.getId(), loader.getSupport().getTripAsIdentifier(trip));
}
}
csvLogger.header("route_ids_with_no_trips.csv", "agency_id,route_id");
for (Route route : _gtfsMutableRelationalDao.getAllRoutes()) {
if (routesWithTrips.contains(route)) {
continue;
}
csvLogger.log("route_ids_with_no_trips.csv", route.getId().getAgencyId(), route.getId().getId());
}
}
|
diff --git a/src/com/designrifts/ultimatethemeui/IconRequest.java b/src/com/designrifts/ultimatethemeui/IconRequest.java
index b73e345..caa64b2 100644
--- a/src/com/designrifts/ultimatethemeui/IconRequest.java
+++ b/src/com/designrifts/ultimatethemeui/IconRequest.java
@@ -1,310 +1,310 @@
/*
* Copyright (C) 2013 Jai Romeo <[email protected]>
*
* 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.designrifts.ultimatethemeui;
import com.designrifts.ultimatethemeui.R;
import com.designrifts.ultimatethemeui.R.id;
import com.designrifts.ultimatethemeui.R.layout;
import com.designrifts.ultimatethemeui.R.string;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class IconRequest extends Activity {
private static final String TAG = "Pkg";
private static final String SD = Environment.getExternalStorageDirectory().getAbsolutePath();
private static final String SAVE_LOC = SD + "/designriftsrequest";
private static final int BUFFER = 2048;
private ProgressDialog pbarDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_blue_dark)));
getActionBar().setDisplayShowHomeEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
pbarDialog = ProgressDialog.show(IconRequest.this,
"Please wait...", "Gathering application info...", true);
Thread designriftsThread = new Thread()
{
@Override
public void run()
{
Looper.prepare();
final File save_loc = new File(SAVE_LOC);
save_loc.mkdirs();
final PackageManager packageManager = getPackageManager();
final StringBuilder sb = new StringBuilder( );
final Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
final List<ResolveInfo> activities = packageManager.queryIntentActivities( intent, 0 );
final int size = activities.size();
if (size == 0) {
finish();
}
for (int i = 0; i < size; i++)
{
final ResolveInfo info = activities.get(i);
final String label = info.loadLabel(packageManager).toString();
final Drawable icon = info.loadIcon(packageManager);
final String pkgName = info.activityInfo.packageName;
final String className = info.activityInfo.name;
- sb.append("<!-- " + label + " -->\n<item component=\""+pkgName+"/"+className+"\" drawable=\""+label+"\" />");
+ sb.append("<!-- " + label + " -->\n<!-- " + pkgName + " -->\n<item component=\""+pkgName+"/"+className+"\" drawable=\""+label.replace(" ", "")+"\" />");
sb.append("\n");
sb.append("\n");
Bitmap bitmap = ((BitmapDrawable)icon).getBitmap();
FileOutputStream fOut;
try {
fOut = new FileOutputStream(SAVE_LOC + "/" + pkgName + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG,100,fOut);
fOut.flush();fOut.close();
} catch (FileNotFoundException e) { }
catch (IOException e) { }
}
try {
- FileWriter fstream = new FileWriter(SAVE_LOC + "/+appfilter.xml");
+ FileWriter fstream = new FileWriter(SAVE_LOC + "/appfilter.xml");
BufferedWriter out = new BufferedWriter(fstream);
out.write(sb.toString());
out.close();
} catch (Exception e){}
createZipFile(SAVE_LOC, true, SD + "/" + android.os.Build.MODEL + ".zip");
// deleteDirectory(save_loc);
handler.sendEmptyMessage(0);
}
};
designriftsThread.start();
}
});
}
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 0:
pbarDialog.dismiss();
final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("application/zip");
final Uri uri = Uri.parse("file://" + SD + "/" + android.os.Build.MODEL + ".zip");
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, (getString(R.string.email_text)));
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{getString(R.string.request_email_addr)});
startActivity(Intent.createChooser(sendIntent, getString(R.string.send_email)));
break;
}
}
};
public static boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}
public static boolean createZipFile(final String path,
final boolean keepDirectoryStructure,
final String out_file) {
final File f = new File(path);
if (!f.canRead() || !f.canWrite())
{
Log.d(TAG, path + " cannot be compressed due to file permissions");
return false;
}
try {
ZipOutputStream zip_out = new ZipOutputStream(
new BufferedOutputStream(
new FileOutputStream(out_file), BUFFER));
if (keepDirectoryStructure)
{
zipFile(path, zip_out, "");
}
else
{
final File files[] = f.listFiles();
for (final File file : files) {
zip_folder(file, zip_out);
}
}
zip_out.close();
} catch (FileNotFoundException e) {
Log.e("File not found", e.getMessage());
return false;
} catch (IOException e) {
Log.e("IOException", e.getMessage());
return false;
}
return true;
}
// keeps directory structure
public static void zipFile(final String path, final ZipOutputStream out, final String relPath) throws IOException
{
final File file = new File(path);
if (!file.exists())
{
Log.d(TAG, file.getName() + " does NOT exist!");
return;
}
final byte[] buf = new byte[1024];
final String[] files = file.list();
if (file.isFile())
{
FileInputStream in = new FileInputStream(file.getAbsolutePath());
try
{
out.putNextEntry(new ZipEntry(relPath + file.getName()));
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
catch (ZipException zipE)
{
Log.d(TAG, zipE.getMessage());
}
finally
{
if (out != null) out.closeEntry();
if (in != null) in.close();
}
}
else if (files.length > 0) // non-empty folder
{
for (int i = 0, length = files.length; i < length; ++i)
{
zipFile(path + "/" + files[i], out, relPath + file.getName() + "/");
}
}
}
/*
*
* @param file
* @param zout
* @throws IOException
*/
private static void zip_folder(File file, ZipOutputStream zout) throws IOException {
byte[] data = new byte[BUFFER];
int read;
if(file.isFile()){
ZipEntry entry = new ZipEntry(file.getName());
zout.putNextEntry(entry);
BufferedInputStream instream = new BufferedInputStream(
new FileInputStream(file));
while((read = instream.read(data, 0, BUFFER)) != -1)
zout.write(data, 0, read);
zout.closeEntry();
instream.close();
} else if (file.isDirectory()) {
String[] list = file.list();
int len = list.length;
for(int i = 0; i < len; i++)
zip_folder(new File(file.getPath() +"/"+ list[i]), zout);
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_blue_dark)));
getActionBar().setDisplayShowHomeEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
pbarDialog = ProgressDialog.show(IconRequest.this,
"Please wait...", "Gathering application info...", true);
Thread designriftsThread = new Thread()
{
@Override
public void run()
{
Looper.prepare();
final File save_loc = new File(SAVE_LOC);
save_loc.mkdirs();
final PackageManager packageManager = getPackageManager();
final StringBuilder sb = new StringBuilder( );
final Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
final List<ResolveInfo> activities = packageManager.queryIntentActivities( intent, 0 );
final int size = activities.size();
if (size == 0) {
finish();
}
for (int i = 0; i < size; i++)
{
final ResolveInfo info = activities.get(i);
final String label = info.loadLabel(packageManager).toString();
final Drawable icon = info.loadIcon(packageManager);
final String pkgName = info.activityInfo.packageName;
final String className = info.activityInfo.name;
sb.append("<!-- " + label + " -->\n<item component=\""+pkgName+"/"+className+"\" drawable=\""+label+"\" />");
sb.append("\n");
sb.append("\n");
Bitmap bitmap = ((BitmapDrawable)icon).getBitmap();
FileOutputStream fOut;
try {
fOut = new FileOutputStream(SAVE_LOC + "/" + pkgName + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG,100,fOut);
fOut.flush();fOut.close();
} catch (FileNotFoundException e) { }
catch (IOException e) { }
}
try {
FileWriter fstream = new FileWriter(SAVE_LOC + "/+appfilter.xml");
BufferedWriter out = new BufferedWriter(fstream);
out.write(sb.toString());
out.close();
} catch (Exception e){}
createZipFile(SAVE_LOC, true, SD + "/" + android.os.Build.MODEL + ".zip");
// deleteDirectory(save_loc);
handler.sendEmptyMessage(0);
}
};
designriftsThread.start();
}
});
}
| public void onCreate(Bundle savedInstanceState) {
getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_blue_dark)));
getActionBar().setDisplayShowHomeEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
pbarDialog = ProgressDialog.show(IconRequest.this,
"Please wait...", "Gathering application info...", true);
Thread designriftsThread = new Thread()
{
@Override
public void run()
{
Looper.prepare();
final File save_loc = new File(SAVE_LOC);
save_loc.mkdirs();
final PackageManager packageManager = getPackageManager();
final StringBuilder sb = new StringBuilder( );
final Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
final List<ResolveInfo> activities = packageManager.queryIntentActivities( intent, 0 );
final int size = activities.size();
if (size == 0) {
finish();
}
for (int i = 0; i < size; i++)
{
final ResolveInfo info = activities.get(i);
final String label = info.loadLabel(packageManager).toString();
final Drawable icon = info.loadIcon(packageManager);
final String pkgName = info.activityInfo.packageName;
final String className = info.activityInfo.name;
sb.append("<!-- " + label + " -->\n<!-- " + pkgName + " -->\n<item component=\""+pkgName+"/"+className+"\" drawable=\""+label.replace(" ", "")+"\" />");
sb.append("\n");
sb.append("\n");
Bitmap bitmap = ((BitmapDrawable)icon).getBitmap();
FileOutputStream fOut;
try {
fOut = new FileOutputStream(SAVE_LOC + "/" + pkgName + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG,100,fOut);
fOut.flush();fOut.close();
} catch (FileNotFoundException e) { }
catch (IOException e) { }
}
try {
FileWriter fstream = new FileWriter(SAVE_LOC + "/appfilter.xml");
BufferedWriter out = new BufferedWriter(fstream);
out.write(sb.toString());
out.close();
} catch (Exception e){}
createZipFile(SAVE_LOC, true, SD + "/" + android.os.Build.MODEL + ".zip");
// deleteDirectory(save_loc);
handler.sendEmptyMessage(0);
}
};
designriftsThread.start();
}
});
}
|
diff --git a/src/com/seekting/study/view/FlowLayout.java b/src/com/seekting/study/view/FlowLayout.java
index f66bc97..7f54552 100644
--- a/src/com/seekting/study/view/FlowLayout.java
+++ b/src/com/seekting/study/view/FlowLayout.java
@@ -1,328 +1,328 @@
package com.seekting.study.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.seekting.study.R;
public class FlowLayout extends ViewGroup {
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
private int horizontalSpacing = 0;
private int verticalSpacing = 0;
private int orientation = 0;
private boolean debugDraw = false;
public FlowLayout(Context context) {
super(context);
this.readStyleParameters(context, null);
}
public FlowLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.readStyleParameters(context, attributeSet);
}
public FlowLayout(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
this.readStyleParameters(context, attributeSet);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int size;
int mode;
if (orientation == HORIZONTAL) {
size = sizeWidth;
mode = modeWidth;
} else {
size = sizeHeight;
mode = modeHeight;
}
int lineThicknessWithSpacing = 0;
int lineThickness = 0;
int lineLengthWithSpacing = 0;
int lineLength;
int prevLinePosition = 0;
int controlMaxLength = 0;
int controlMaxThickness = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(
MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth),
MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight)
);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int hSpacing = this.getHorizontalSpacing(lp);
int vSpacing = this.getVerticalSpacing(lp);
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int childLength;
int childThickness;
int spacingLength;
int spacingThickness;
if (orientation == HORIZONTAL) {
childLength = childWidth;
childThickness = childHeight;
spacingLength = hSpacing;
spacingThickness = vSpacing;
} else {
childLength = childHeight;
childThickness = childWidth;
spacingLength = vSpacing;
spacingThickness = hSpacing;
}
lineLength = lineLengthWithSpacing + childLength;
lineLengthWithSpacing = lineLength + spacingLength;
boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size);
if (newLine) {
prevLinePosition = prevLinePosition + lineThicknessWithSpacing;
lineThickness = childThickness;
lineLength = childLength;
lineThicknessWithSpacing = childThickness + spacingThickness;
lineLengthWithSpacing = lineLength + spacingLength;
}
lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness);
lineThickness = Math.max(lineThickness, childThickness);
int posX;
int posY;
if (orientation == HORIZONTAL) {
posX = getPaddingLeft() + lineLength - childLength;
posY = getPaddingTop() + prevLinePosition;
} else {
posX = getPaddingLeft() + prevLinePosition;
posY = getPaddingTop() + lineLength - childHeight;
}
lp.setPosition(posX, posY);
controlMaxLength = Math.max(controlMaxLength, lineLength);
controlMaxThickness = prevLinePosition + lineThickness;
}
/* need to take far side padding into account */
if (orientation == HORIZONTAL) {
controlMaxLength += getPaddingRight();
- controlMaxThickness += getPaddingBottom();
+ controlMaxThickness = controlMaxThickness+getPaddingBottom()+getPaddingTop();
} else {
controlMaxLength += getPaddingBottom();
controlMaxThickness += getPaddingRight();
}
if (orientation == HORIZONTAL) {
this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec));
} else {
this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec));
}
}
private int getVerticalSpacing(LayoutParams lp) {
int vSpacing;
if (lp.verticalSpacingSpecified()) {
vSpacing = lp.verticalSpacing;
} else {
vSpacing = this.verticalSpacing;
}
return vSpacing;
}
private int getHorizontalSpacing(LayoutParams lp) {
int hSpacing;
if (lp.horizontalSpacingSpecified()) {
hSpacing = lp.horizontalSpacing;
} else {
hSpacing = this.horizontalSpacing;
}
return hSpacing;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
child.layout(lp.x, lp.y, lp.x + child.getMeasuredWidth(), lp.y + child.getMeasuredHeight());
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean more = super.drawChild(canvas, child, drawingTime);
this.drawDebugInfo(canvas, child);
return more;
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attributeSet) {
return new LayoutParams(getContext(), attributeSet);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
private void readStyleParameters(Context context, AttributeSet attributeSet) {
TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.FlowLayout);
try {
horizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_horizontalSpacing, 0);
verticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_verticalSpacing, 0);
orientation = a.getInteger(R.styleable.FlowLayout_orientation, HORIZONTAL);
debugDraw = a.getBoolean(R.styleable.FlowLayout_debugDraw, false);
} finally {
a.recycle();
}
}
private void drawDebugInfo(Canvas canvas, View child) {
if (!debugDraw) {
return;
}
Paint childPaint = this.createPaint(0xffffff00);
Paint layoutPaint = this.createPaint(0xff00ff00);
Paint newLinePaint = this.createPaint(0xffff0000);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.horizontalSpacing > 0) {
float x = child.getRight();
float y = child.getTop() + child.getHeight() / 2.0f;
canvas.drawLine(x, y, x + lp.horizontalSpacing, y, childPaint);
canvas.drawLine(x + lp.horizontalSpacing - 4.0f, y - 4.0f, x + lp.horizontalSpacing, y, childPaint);
canvas.drawLine(x + lp.horizontalSpacing - 4.0f, y + 4.0f, x + lp.horizontalSpacing, y, childPaint);
} else if (this.horizontalSpacing > 0) {
float x = child.getRight();
float y = child.getTop() + child.getHeight() / 2.0f;
canvas.drawLine(x, y, x + this.horizontalSpacing, y, layoutPaint);
canvas.drawLine(x + this.horizontalSpacing - 4.0f, y - 4.0f, x + this.horizontalSpacing, y, layoutPaint);
canvas.drawLine(x + this.horizontalSpacing - 4.0f, y + 4.0f, x + this.horizontalSpacing, y, layoutPaint);
}
if (lp.verticalSpacing > 0) {
float x = child.getLeft() + child.getWidth() / 2.0f;
float y = child.getBottom();
canvas.drawLine(x, y, x, y + lp.verticalSpacing, childPaint);
canvas.drawLine(x - 4.0f, y + lp.verticalSpacing - 4.0f, x, y + lp.verticalSpacing, childPaint);
canvas.drawLine(x + 4.0f, y + lp.verticalSpacing - 4.0f, x, y + lp.verticalSpacing, childPaint);
} else if (this.verticalSpacing > 0) {
float x = child.getLeft() + child.getWidth() / 2.0f;
float y = child.getBottom();
canvas.drawLine(x, y, x, y + this.verticalSpacing, layoutPaint);
canvas.drawLine(x - 4.0f, y + this.verticalSpacing - 4.0f, x, y + this.verticalSpacing, layoutPaint);
canvas.drawLine(x + 4.0f, y + this.verticalSpacing - 4.0f, x, y + this.verticalSpacing, layoutPaint);
}
if (lp.newLine) {
if (orientation == HORIZONTAL) {
float x = child.getLeft();
float y = child.getTop() + child.getHeight() / 2.0f;
canvas.drawLine(x, y - 6.0f, x, y + 6.0f, newLinePaint);
} else {
float x = child.getLeft() + child.getWidth() / 2.0f;
float y = child.getTop();
canvas.drawLine(x - 6.0f, y, x + 6.0f, y, newLinePaint);
}
}
}
private Paint createPaint(int color) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setStrokeWidth(2.0f);
return paint;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
private static int NO_SPACING = -1;
private int x;
private int y;
private int horizontalSpacing = NO_SPACING;
private int verticalSpacing = NO_SPACING;
private boolean newLine = false;
public LayoutParams(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.readStyleParameters(context, attributeSet);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams layoutParams) {
super(layoutParams);
}
public boolean horizontalSpacingSpecified() {
return horizontalSpacing != NO_SPACING;
}
public boolean verticalSpacingSpecified() {
return verticalSpacing != NO_SPACING;
}
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
private void readStyleParameters(Context context, AttributeSet attributeSet) {
TypedArray a = context.obtainStyledAttributes(attributeSet, R.styleable.FlowLayout_LayoutParams);
try {
horizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_LayoutParams_layout_horizontalSpacing, NO_SPACING);
verticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_LayoutParams_layout_verticalSpacing, NO_SPACING);
newLine = a.getBoolean(R.styleable.FlowLayout_LayoutParams_layout_newLine, false);
} finally {
a.recycle();
}
}
}
}
| true | true | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int size;
int mode;
if (orientation == HORIZONTAL) {
size = sizeWidth;
mode = modeWidth;
} else {
size = sizeHeight;
mode = modeHeight;
}
int lineThicknessWithSpacing = 0;
int lineThickness = 0;
int lineLengthWithSpacing = 0;
int lineLength;
int prevLinePosition = 0;
int controlMaxLength = 0;
int controlMaxThickness = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(
MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth),
MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight)
);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int hSpacing = this.getHorizontalSpacing(lp);
int vSpacing = this.getVerticalSpacing(lp);
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int childLength;
int childThickness;
int spacingLength;
int spacingThickness;
if (orientation == HORIZONTAL) {
childLength = childWidth;
childThickness = childHeight;
spacingLength = hSpacing;
spacingThickness = vSpacing;
} else {
childLength = childHeight;
childThickness = childWidth;
spacingLength = vSpacing;
spacingThickness = hSpacing;
}
lineLength = lineLengthWithSpacing + childLength;
lineLengthWithSpacing = lineLength + spacingLength;
boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size);
if (newLine) {
prevLinePosition = prevLinePosition + lineThicknessWithSpacing;
lineThickness = childThickness;
lineLength = childLength;
lineThicknessWithSpacing = childThickness + spacingThickness;
lineLengthWithSpacing = lineLength + spacingLength;
}
lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness);
lineThickness = Math.max(lineThickness, childThickness);
int posX;
int posY;
if (orientation == HORIZONTAL) {
posX = getPaddingLeft() + lineLength - childLength;
posY = getPaddingTop() + prevLinePosition;
} else {
posX = getPaddingLeft() + prevLinePosition;
posY = getPaddingTop() + lineLength - childHeight;
}
lp.setPosition(posX, posY);
controlMaxLength = Math.max(controlMaxLength, lineLength);
controlMaxThickness = prevLinePosition + lineThickness;
}
/* need to take far side padding into account */
if (orientation == HORIZONTAL) {
controlMaxLength += getPaddingRight();
controlMaxThickness += getPaddingBottom();
} else {
controlMaxLength += getPaddingBottom();
controlMaxThickness += getPaddingRight();
}
if (orientation == HORIZONTAL) {
this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec));
} else {
this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec));
}
}
| protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec) - this.getPaddingRight() - this.getPaddingLeft();
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
int size;
int mode;
if (orientation == HORIZONTAL) {
size = sizeWidth;
mode = modeWidth;
} else {
size = sizeHeight;
mode = modeHeight;
}
int lineThicknessWithSpacing = 0;
int lineThickness = 0;
int lineLengthWithSpacing = 0;
int lineLength;
int prevLinePosition = 0;
int controlMaxLength = 0;
int controlMaxThickness = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(
MeasureSpec.makeMeasureSpec(sizeWidth, modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeWidth),
MeasureSpec.makeMeasureSpec(sizeHeight, modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : modeHeight)
);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int hSpacing = this.getHorizontalSpacing(lp);
int vSpacing = this.getVerticalSpacing(lp);
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
int childLength;
int childThickness;
int spacingLength;
int spacingThickness;
if (orientation == HORIZONTAL) {
childLength = childWidth;
childThickness = childHeight;
spacingLength = hSpacing;
spacingThickness = vSpacing;
} else {
childLength = childHeight;
childThickness = childWidth;
spacingLength = vSpacing;
spacingThickness = hSpacing;
}
lineLength = lineLengthWithSpacing + childLength;
lineLengthWithSpacing = lineLength + spacingLength;
boolean newLine = lp.newLine || (mode != MeasureSpec.UNSPECIFIED && lineLength > size);
if (newLine) {
prevLinePosition = prevLinePosition + lineThicknessWithSpacing;
lineThickness = childThickness;
lineLength = childLength;
lineThicknessWithSpacing = childThickness + spacingThickness;
lineLengthWithSpacing = lineLength + spacingLength;
}
lineThicknessWithSpacing = Math.max(lineThicknessWithSpacing, childThickness + spacingThickness);
lineThickness = Math.max(lineThickness, childThickness);
int posX;
int posY;
if (orientation == HORIZONTAL) {
posX = getPaddingLeft() + lineLength - childLength;
posY = getPaddingTop() + prevLinePosition;
} else {
posX = getPaddingLeft() + prevLinePosition;
posY = getPaddingTop() + lineLength - childHeight;
}
lp.setPosition(posX, posY);
controlMaxLength = Math.max(controlMaxLength, lineLength);
controlMaxThickness = prevLinePosition + lineThickness;
}
/* need to take far side padding into account */
if (orientation == HORIZONTAL) {
controlMaxLength += getPaddingRight();
controlMaxThickness = controlMaxThickness+getPaddingBottom()+getPaddingTop();
} else {
controlMaxLength += getPaddingBottom();
controlMaxThickness += getPaddingRight();
}
if (orientation == HORIZONTAL) {
this.setMeasuredDimension(resolveSize(controlMaxLength, widthMeasureSpec), resolveSize(controlMaxThickness, heightMeasureSpec));
} else {
this.setMeasuredDimension(resolveSize(controlMaxThickness, widthMeasureSpec), resolveSize(controlMaxLength, heightMeasureSpec));
}
}
|
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/testSecMec.java b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/testSecMec.java
index 5eeb16dac..a3b4be079 100644
--- a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/testSecMec.java
+++ b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/testSecMec.java
@@ -1,1041 +1,1043 @@
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.derbynet.testSecMec
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.derbyTesting.functionTests.tests.derbynet;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.DriverManager;
import javax.sql.DataSource;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import org.apache.derby.tools.JDBCDisplayUtil;
import org.apache.derby.tools.ij;
import org.apache.derby.drda.NetworkServerControl;
import org.apache.derbyTesting.functionTests.util.TestUtil;
import java.io.*;
import java.net.InetAddress;
import java.util.Hashtable;
import java.util.Properties;
import java.lang.reflect.*;
/**
* This class tests the security mechanisms supported by Network Server
* Network server supports SECMEC_EUSRIDPWD, SECMEC_USRIDPWD, SECMEC_USRIDONL
* and SECMEC_USRSSBPWD.
*
* -----------------------------------------------------------------
* Security Mechanism | secmec codepoint value | User friendly name
* -----------------------------------------------------------------
* USRIDONL | 0x04 | USER_ONLY_SECURITY
* USRIDPWD | 0x03 | CLEAR_TEXT_PASSWORD_SECURITY
* EUSRIDPWD | 0x09 | ENCRYPTED_USER_AND_PASSWORD_SECURITY
* USRSSBPWD | 0x08 | STRONG_PASSWORD_SUBSTITUTE_SECURITY
* -----------------------------------------------------------------
*
* Key points:
* 1)Server and client support encrypted userid/password (EUSRIDPWD) via the
* use of Diffie Helman key-agreement protocol - however current Open Group DRDA
* specifications imposes small prime and base generator values (256 bits) that
* prevents other JCE's to be used as java cryptography providers - typical
* minimum security requirements is usually of 1024 bits (512-bit absolute
* minimum) when using DH key-agreement protocol to generate a session key.
*
* (Reference: DDM manual, page 281 and 282. Section: Generating the shared
* private key. DRDA's diffie helman agreed public values for prime are 256
* bits. The spec gives the public values for the prime, generator and the size
* of exponent required for DH . These values must be used as is to generate a
* shared private key.)
*
* Encryption is done using JCE. Hence JCE support of the necessary algorithm is
* required for a particular security mechanism to work. Thus even though the
* server and client have code to support EUSRIDPWD, this security mechanism
* will not work in all JVMs.
*
* JVMs where support for DH(32byte prime) is not available and thus EUSRIDPWD
* wont work are Sun JVM (versions 1.3.1,1.4.1,1.4.2,1.5) and IBM JVM (versions
* 1.3.1 and some old versions of 1.4.2 (in 2004) )
*
* JVMs where support for DH(32bytes prime) is available and thus EUSRIDPWD will
* work are IBM JVM [versions 1.4.1, later versions of 1.4.2 (from 2005), 1.5]
*
* #2) JCC 2.6 client does some automatic upgrade of security mechanism in one
* case. Logic is as follows:
* If client sends USRIDPWD to server and server rejects this
* and says it accepts only EUSRIDPWD, in that case JCC 2.6 will upgrade the
* security mechanism to EUSRIDPWD and retry the request with EUSRIDPWD.
* This switching will also override the security mechanism specified by user.
* Thus if JCC client is running with Sun JVM 1.4.2 and even though Sun JCE
* does not have support for algorithms needed for EUSRIDPWD, the JCC client
* will still try to switch to EUSRIDPWD and throw an exception with
* ClassNotFoundException for the IBM JCE.
*
* - Default security mechanism is USRIDPWD(0x03)
* - If securityMechanism is not explicitly specified on connection request
* and if no user specified, an exception is thrown - Null userid not supported
* - If securityMechanism is not explicitly specified on connection request,
* and if no password is specified, an exception is thrown - null password not supported
* If securityMechanism is explicitly specified to be USRIDONL, then a password
* is not required. But in other cases (EUSRIDPWD, USRIDPWD, USRSSBPWD) if
* password is null, an exception with the message 'a null password not valid'
* will be thrown.
* - On datasource, setting a security mechanism works. It also allows a security
* mechanism of USRIDONL to be set on datasource unlike jcc 2.4.
*
* #3)JCC 2.4 client behavior
* Default security mechanism used is USRIDPWD (0x03)
* If securityMechanism is not explicitly specified on connection request,
* and if no user is specified, an exception is thrown. - Null userid not supported.
* If securityMechanism is not explicitly specified on connection request,
* and if no password is specified, an exception is thrown - null password not supported
* If security mechanism is specified, jcc client will not override the security mechanism.
* If securityMechanism is explicitly specified to be USRIDONL, then a password
* is not required. But in other cases (EUSRIDPWD,USRIDPWD) if password is null
* - an exception with the message 'a null password not valid' will be thrown.
* On datasource, setting a security mechanism does not work (bug). It defaults
* to USRIDPWD. Setting a value of USRIDONL or EUSRIDPWD does not seem to have
* an effect.
*
* #4) Note, if server restricts the client connections based on security mechanism
* by setting derby.drda.securityMechanism, in that case the clients will see an
* error similar to this
* "Connection authorization failure occurred. Reason: security mechanism not supported"
*
* #5) USRSSBPWD - Strong password substitute is only supported starting from
* Apache Derby 10.2.
* NOTE: USRSSBPWD only works with the derby network client driver for now.
* ----
*/
public class testSecMec extends dataSourcePermissions_net
{
// Need this to keep track of database has been created or not
// to avoid case of DERBY-300
private static boolean dbNotCreated = true;
// values for derby.drda.securityMechanism property
private static String[] derby_drda_securityMechanism = { null, //not set
"USER_ONLY_SECURITY", "CLEAR_TEXT_PASSWORD_SECURITY",
"ENCRYPTED_USER_AND_PASSWORD_SECURITY",
"STRONG_PASSWORD_SUBSTITUTE_SECURITY", "INVALID_VALUE", "" };
// possible interesting combinations with respect to security mechanism
// upgrade logic for user attribute
private static String[] USER_ATTRIBUTE = {"calvin",null};
// possible interesting combinations with respect to security mechanism
// upgrade logic for password attribute
private static String[] PWD_ATTRIBUTE = {"hobbes",null};
private static int NETWORKSERVER_PORT;
private static NetworkServerControl networkServer = null;
private testSecMec(SwitchablePrintStream consoleLogStream,
PrintStream originalStream,
FileOutputStream shutdownLogStream,
SwitchablePrintStream consoleErrLogStream,
PrintStream originalErrStream,
FileOutputStream shutdownErrLogStream){
super(consoleLogStream,
originalStream,
shutdownLogStream,
consoleErrLogStream,
originalErrStream,
shutdownErrLogStream);
}
public static void main(String[] args) throws Exception {
// Load harness properties.
ij.getPropertyArg(args);
String hostName = TestUtil.getHostName();
if (hostName.equals("localhost"))
NETWORKSERVER_PORT = 20000;
else
NETWORKSERVER_PORT = 1527;
// "runTest()" is going to try to connect to the database through
// the server at port NETWORKSERVER_PORT. Thus, we have to
// start the server on that port before calling runTest.
try {
TestUtil.loadDriver();
} catch (Exception e) {
e.printStackTrace();
}
PrintStream originalStream = System.out;
FileOutputStream shutdownLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.std.log");
SwitchablePrintStream consoleLogStream =
new SwitchablePrintStream( originalStream );
PrintStream originalErrStream = System.err;
FileOutputStream shutdownErrLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.err.log");
SwitchablePrintStream consoleErrLogStream =
new SwitchablePrintStream( originalErrStream );
System.setOut( consoleLogStream );
System.setErr( consoleErrLogStream );
// Start server with a specific value for derby.drda.securityMechanism
// and run tests. Note connections will be successful or not depending on
// derby.drda.securityMechanism property specified on the server (DERBY-928)
// @see
// org.apache.derby.iapi.reference.Property#DRDA_PROP_SECURITYMECHANISM
for ( int i = 0; i < derby_drda_securityMechanism.length; i++)
{
if (derby_drda_securityMechanism[i]!=null)
System.setProperty("derby.drda.securityMechanism",derby_drda_securityMechanism[i]);
System.out.println("----------------------------------------------");
System.out.println("Testing with derby.drda.securityMechanism="+
System.getProperty("derby.drda.securityMechanism"));
// Start the NetworkServer on another thread, unless it's a remote host
if (hostName.equals("localhost"))
{
try
{
networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT);
networkServer.start(null);
}catch(Exception e)
{
if ( derby_drda_securityMechanism[i].equals("INVALID_VALUE")||
derby_drda_securityMechanism[i].equals(""))
{
System.out.println("EXPECTED EXCEPTION "+ e.getMessage());
continue;
}
}
// Wait for the NetworkServer to start.
- if (!isServerStarted(networkServer, 60))
- System.exit(-1);
+ if (!isServerStarted(networkServer, 60)) {
+ System.out.println("FAIL: Server failed to respond to ping - ending test");
+ break;
+ }
}
// Now, go ahead and run the test.
try {
testSecMec tester =
new testSecMec(consoleLogStream,
originalStream,
shutdownLogStream,
consoleErrLogStream,
originalErrStream,
shutdownErrLogStream);
// Now run the test, note connections will be successful or
// throw an exception depending on derby.drda.securityMechanism
// property specified on the server
tester.runTest();
} catch (Exception e) {
// if we catch an exception of some sort, we need to make sure to
// close our streams before returning; otherwise, we can get
// hangs in the harness. SO, catching all exceptions here keeps
// us from exiting before closing the necessary streams.
System.out.println("FAIL - Exiting due to unexpected error: " +
e.getMessage());
e.printStackTrace();
}
// Shutdown the server.
if (hostName.equals("localhost"))
{
consoleLogStream.switchOutput( shutdownLogStream );
consoleErrLogStream.switchOutput( shutdownErrLogStream );
networkServer.shutdown();
consoleLogStream.flush();
// how do we do this with the new api?
//networkServer.join();
Thread.sleep(5000);
consoleLogStream.switchOutput( originalStream );
consoleErrLogStream.switchOutput( originalErrStream );
}
// Now we want to test
}
System.out.println("Completed testSecMec");
originalStream.close();
shutdownLogStream.close();
originalErrStream.close();
shutdownErrLogStream.close();
}
// Indicates userid/encrypted password security mechanism.
static final short SECMEC_EUSRIDPWD = 0x09;
// Indicates userid only security mechanism.
static final short SECMEC_USRIDONL = 0x04;
// Indicates userid/encrypted password security mechanism.
static final short SECMEC_USRENCPWD = 0x07;
// Indicates userid/new password security mechanism.
static final short SECMEC_USRIDNWPWD = 0x05;
// Indicates userid/password security mechanism.
static final short SECMEC_USRIDPWD = 0x03;
// Indicates strong password substitute security mechanism.
static final short SECMEC_USRSSBPWD = 0x08;
// client and server recognize these secmec values
private static short[] SECMEC_ATTRIBUTE = {
SECMEC_USRIDONL,
SECMEC_USRIDPWD,
SECMEC_EUSRIDPWD,
SECMEC_USRSSBPWD
};
/**
* Test cases for security mechanism
* ---------------------------------------------------------------
* T1 - default , no user PASS (for derbyclient)
* T2 - user only PASS (for derbyclient)
* T3 - user,password PASS (only for derbynet)
* T4 - user,password, security mechanism not set FAIL
* T5 - user,password, security mechanism set to SECMEC_EUSRIDPWD PASS/FAIL
* (Fails with Sun JVM as EUSRIDPWD secmec cannot be used)
* T6 - user, security mechanism set to SECMEC_USRIDONL PASS
* T7 - user,password, security mechanism set to SECMEC_USRENCPWD FAIL
* Test with datasource as well as DriverManager
* T8 - user,password security mechanism set to SECMEC_USRIDONL PASS
* T9 - user,password security mechanism set to SECMEC_USRSSBPWD PASS
* Test with datasource as well as DriverManager
* Note, that with DERBY928, the pass/fail for the connections
* will depend on the security mechanism specified at the server by property
* derby.drda.securityMechanism. Please check out the following html file
* http://issues.apache.org/jira/secure/attachment/12322971/Derby928_Table_SecurityMechanisms..htm
* for a combination of url/security mechanisms and the expected results
*/
protected void runTest()
{
// Test cases with get connection via drivermanager and using
// different security mechanisms.
// Network server supports SECMEC_USRIDPWD, SECMEC_USRIDONL,
// SECMEC_EUSRIDPWD and USRSSBPWD (derby network client only)
System.out.println("Checking security mechanism authentication with DriverManager");
// DERBY-300; Creation of SQLWarning on a getConnection causes hang on
// 131 vms when server and client are in same vm.
// To avoid hitting this case with 1.3.1 vms, dont try to send create=true
// if database is already created as otherwise it will lead to a SQLWarning
if ( dbNotCreated )
{
getConnectionUsingDriverManager(getJDBCUrl("wombat;create=true","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDPWD),"T4:");
dbNotCreated = false;
}
else
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDPWD),"T4:");
getConnectionUsingDriverManager(getJDBCUrl("wombat",null),"T1:");
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=max"),"T2:");
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee"),"T3:");
// Please note: EUSRIDPWD security mechanism in DRDA uses Diffie-Helman for generation of shared keys.
// The spec specifies the prime to use for DH which is 32 bytes and this needs to be used as is.
// Sun JCE does not support a prime of 32 bytes for Diffie Helman and some
// older versions of IBM JCE ( 1.4.2) also do not support it.
// Hence the following call to get connection might not be successful when
// client is running in JVM where the JCE does not support the DH (32 byte prime)
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_EUSRIDPWD),"T5:");
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;securityMechanism="+SECMEC_USRIDONL),"T6:");
// disable as ibm142 and sun jce doesnt support DH prime of 32 bytes
//getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRENCPWD),"T7:");
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRIDONL),"T8:");
// Test strong password substitute DRDA security mechanism (only works with DerbyClient driver right now)
getConnectionUsingDriverManager(getJDBCUrl("wombat","user=neelima;password=lee;securityMechanism="+SECMEC_USRSSBPWD),"T9:");
getConnectionUsingDataSource();
// regression test for DERBY-1080
testDerby1080();
// test for DERBY-962
testAllCombinationsOfUserPasswordSecMecInput();
// test USRSSBPWD (DERBY-528) with Derby BUILTIN authentication scheme
// both with none and USRSSBPWD specified DRDA SecMec upon
// starting the network server.
String serverSecurityMechanism =
System.getProperty("derby.drda.securityMechanism");
if ((serverSecurityMechanism == null) ||
(serverSecurityMechanism.equals(
"STRONG_PASSWORD_SUBSTITUTE_SECURITY")))
{
testUSRSSBPWD_with_BUILTIN();
}
}
/**
* Get connection from datasource and also set security mechanism
*/
public void getConnectionUsingDataSource()
{
// bug in jcc, throws error with null password
//testSecurityMechanism("sarah",null,new Short(SECMEC_USRIDONL),"SECMEC_USRIDONL:");
testSecurityMechanism("john","sarah",new Short(SECMEC_USRIDPWD),"SECMEC_USRIDPWD:");
// Possible bug in JCC, hence disable this test for JCC framework only
// the security mechanism when set on JCC datasource does not seem to
// have an effect. JCC driver is sending a secmec of 3( USRIDPWD) to
// the server even though the security mechanism on datasource is set to
// EUSRIDPWD (9)
if (!TestUtil.isJCCFramework())
{
// Please note: EUSRIDPWD security mechanism in DRDA uses Diffie-Helman for generation of shared keys.
// The spec specifies the prime to use for DH which is 32 bytes and this needs to be used as is.
// Sun JCE does not support a prime of 32 bytes for Diffie Helman and some
// older versions of IBM JCE ( 1.4.2) also do not support it.
// Hence the following call to get connection might not be successful when
// client is running in JVM where the JCE does not support the DH (32 byte prime)
testSecurityMechanism("john","sarah",new Short(SECMEC_EUSRIDPWD),"SECMEC_EUSRIDPWD:");
// JCC does not support USRSSBPWD security mechanism
testSecurityMechanism("john","sarah",new Short(SECMEC_USRSSBPWD),"SECMEC_USRSSBPWD:");
}
}
public void testSecurityMechanism(String user, String password,Short secmec,String msg)
{
Connection conn;
String securityMechanismProperty = "SecurityMechanism";
Class[] argType = { Short.TYPE };
String methodName = TestUtil.getSetterName(securityMechanismProperty);
Object[] args = new Short[1];
args[0] = secmec;
try {
DataSource ds = getDS("wombat", user,password);
Method sh = ds.getClass().getMethod(methodName, argType);
sh.invoke(ds, args);
conn = ds.getConnection();
conn.close();
System.out.println(msg +" OK");
}
catch (SQLException sqle)
{
// Exceptions expected in certain cases depending on JCE used for
// running the test. hence printing message instead of stack traces
// here.
System.out.println(msg +"EXCEPTION testSecurityMechanism() " + sqle.getMessage());
dumpSQLException(sqle.getNextException());
}
catch (Exception e)
{
System.out.println("UNEXPECTED EXCEPTION!!!" +msg);
e.printStackTrace();
}
}
public void getConnectionUsingDriverManager(String dbUrl, String msg)
{
try
{
DriverManager.getConnection(dbUrl);
System.out.println(msg +" "+dbUrl );
}
catch(SQLException sqle)
{
// Ideally - we would print stack trace of nested SQLException for
// any unexpected exception.
// But in this testcase, one test can give an exception in one JCE
// implementation and in some JCE's the test can pass.
// Hence printing the messages instead of stack traces.
System.out.println(msg +" "+dbUrl +" - EXCEPTION "+ sqle.getMessage());
dumpSQLException(sqle.getNextException());
}
}
/**
* Test different interesting combinations of user,password, security mechanism
* for testing security mechanism upgrade logic. This test has been added
* as part of DERBY-962. Two things have been fixed in DERBY-962, affects
* only client behavior.
*
* 1)Upgrade logic should not override security mechanism if it has been
* explicitly set in connection request (either via DriverManager or
* using DataSource)
*
* 2)Upgrade security mechanism to a more secure one , ie preferably
* to encrypted userid and password if the JVM in which the client is
* running has support for it.
*
* Details are:
* If security mechanism is not specified as part of the connection request,
* then client will do an automatic switching (upgrade) of
* security mechanism to use. The logic is as follows :
* if password is available, and if the JVM in which the client is running
* supports EUSRIDPWD mechanism, in that case the security mechanism is
* upgraded to EUSRIDPWD.
* if password is available, and if the JVM in which the client is running
* does not support EUSRIDPWD mechanism, in that case the client will then
* default to USRIDPWD.
* Also see DERBY-962 http://issues.apache.org/jira/browse/DERBY-962
* <BR>
* To understand which JVMs support EUSRIDPWD or not, please see class level
* comments (#1)
* <BR>
* The expected output from this test will depend on the following
* -- the client behavior (JCC 2.4, JCC2.6 or derby client).For the derby client,
* the table below represents what security mechanism the client will send
* to server.
* -- See class level comments (#2,#3) to understand the JCC2.6 and JCC2.4
* behavior
* -- Note: in case of derby client, if no user is specified, user defaults to APP.
* -- Will depend on if the server has been started with derby.drda.securityMechanism
* and to the value it is set to. See main method to check if server is using the
* derby.drda.securityMechanism to restrict client connections based on
* security mechanism.
*
TABLE with all different combinations of userid, password,
security mechanism of derby client that is covered by this testcase if test
is run against IBM15 and JDK15.
IBM15 supports eusridpwd, whereas SunJDK15 doesnt support EUSRIDPWD
Security Mechanisms supported by derby server and client
====================================================================
|SecMec |codepoint value| User friendly name |
====================================================================
|USRIDONL | 0x04 | USER_ONLY_SECURITY |
|USRIDPWD | 0x03 | CLEAR_TEXT_PASSWORD_SECURITY |
|EUSRIDPWD | 0x09 | ENCRYPTED_USER_AND_PASSWORD_SECURITY|
|USRSSBPWD | 0x08 | STRONG_PASSWORD_SUBSTITUTE_SECURITY |
=====================================================================
Explanation of columns in table.
a) Connection request specifies a user or not.
Note: if no user is specified, client defaults to APP
b) Connection request specifies a password or not
c) Connection request specifies securityMechanism or not. the valid
values are 4(USRIDONL), 3(USRIDPWD), 9(EUSRIDPWD) and 8(USRSSBPWD).
d) support eusridpwd means whether this jvm supports encrypted userid/
password security mechanism or not. A value of Y means it supports
and N means no.
The next three columns specify what the client sends to the server
e) Does client send user information
f) Does client send password information
g) What security mechanism value (secmec value) is sent to server.
SecMec refers to securityMechanism.
Y means yes, N means No, - or blank means not specified.
Err stands for error.
Err(1) stands for null password not supported
Err(2) stands for case when the JCE does not support encrypted userid and
password security mechanism.
----------------------------------------------------------------
| url connection | support | Client sends to Server |
|User |Pwd |secmec |eusridpwd |User Pwd SecMec |
|#a |#b |#c |#d |#e #f #g |
|---------------------------------------------------------------|
=================================================================
|SecMec not specified on connection request
=================================================================
|Y |Y |- |Y |Y Y 9 |
|----------------------------------------------------------------
| |Y |- |Y |Y Y 9 |
-----------------------------------------------------------------
|Y | |- |Y |Y N 4 |
-----------------------------------------------------------------
| | |- |Y |Y N 4 |
=================================================================
|Y |Y |- |N |Y Y 3 |
|----------------------------------------------------------------
| |Y |- |N |Y Y 3 |
-----------------------------------------------------------------
|Y | |- |N |Y N 4 |
-----------------------------------------------------------------
| | |- |N |Y N 4 |
=================================================================
SecMec specified to 3 (clear text userid and password)
=================================================================
|Y |Y |3 |Y |Y Y 3 |
|----------------------------------------------------------------
| |Y |3 |Y |Y Y 3 |
-----------------------------------------------------------------
|Y | |3 |Y |- - Err1 |
-----------------------------------------------------------------
| | |3 |Y |- - Err1 |
=================================================================
|Y |Y |3 |N |Y Y 3 |
|----------------------------------------------------------------
| |Y |3 |N |Y Y 3 |
-----------------------------------------------------------------
|Y | |3 |N |- - Err1 |
-----------------------------------------------------------------
| | |3 |N |- - Err1 |
=================================================================
SecMec specified to 9 (encrypted userid/password)
=================================================================
|Y |Y |9 |Y |Y Y 9 |
|----------------------------------------------------------------
| |Y |9 |Y |Y Y 9 |
-----------------------------------------------------------------
|Y | |9 |Y | - - Err1 |
-----------------------------------------------------------------
| | |9 |Y | - - Err1 |
=================================================================
|Y |Y |9 |N | - - Err2 |
|----------------------------------------------------------------
| |Y |9 |N | - - Err2 |
-----------------------------------------------------------------
|Y | |9 |N | - - Err1 |
-----------------------------------------------------------------
| | |9 |N | - - Err1 |
=================================================================
SecMec specified to 4 (userid only security)
=================================================================
|Y |Y |4 |Y |Y N 4 |
|----------------------------------------------------------------
| |Y |4 |Y |Y N 4 |
-----------------------------------------------------------------
|Y | |4 |Y |Y N 4 |
-----------------------------------------------------------------
| | |4 |Y |Y N 4 |
=================================================================
|Y |Y |4 |N |Y N 4 |
|----------------------------------------------------------------
| |Y |4 |N |Y N 4 |
-----------------------------------------------------------------
|Y | |4 |N |Y N 4 |
-----------------------------------------------------------------
| | |4 |N |Y N 4 |
=================================================================
SecMec specified to 8 (strong password substitute)
=================================================================
|Y |Y |8 |Y |Y Y 8 |
|----------------------------------------------------------------
| |Y |8 |Y |Y Y 8 |
-----------------------------------------------------------------
|Y | |8 |Y | - - Err1 |
-----------------------------------------------------------------
| | |8 |Y | - - Err1 |
=================================================================
|Y |Y |8 |N | - Y 8 |
|----------------------------------------------------------------
| |Y |8 |N | - Y 8 |
-----------------------------------------------------------------
|Y | |8 |N | - - Err1 |
-----------------------------------------------------------------
| | |8 |N | - - Err1 |
=================================================================
*/
public void testAllCombinationsOfUserPasswordSecMecInput() {
// Try following combinations:
// user { null, user attribute given}
// password {null, pwd specified}
// securityMechanism attribute specified and not specified.
// try with different security mechanism values - {encrypted
// useridpassword, userid only, clear text userid &password)
String urlAttributes = null;
System.out.println("******testAllCombinationsOfUserPasswordsSecMecInput***");
for (int k = 0; k < USER_ATTRIBUTE.length; k++) {
for (int j = 0; j < PWD_ATTRIBUTE.length; j++) {
urlAttributes = "";
if (USER_ATTRIBUTE[k] != null)
urlAttributes += "user=" + USER_ATTRIBUTE[k] +";";
if (PWD_ATTRIBUTE[j] != null)
urlAttributes += "password=" + PWD_ATTRIBUTE[j] +";";
// removing the last semicolon that we added here, because
// on call to getJDBCUrl in dataSourcePermissions_net, another
// semicolon will get added for jcc and jcc will not like it.
if (urlAttributes.length() >= 1)
urlAttributes = urlAttributes.substring(0,urlAttributes.length()-1);
// case - do not specify securityMechanism explicitly in the url
// get connection via driver manager and datasource.
getConnectionUsingDriverManager(getJDBCUrl("wombat",
urlAttributes), "Test:");
getDataSourceConnection(USER_ATTRIBUTE[k],PWD_ATTRIBUTE[j],
"TEST_DS("+urlAttributes+")");
for (int i = 0; i < SECMEC_ATTRIBUTE.length; i++) {
// case - specify securityMechanism attribute in url
// get connection using DriverManager
getConnectionUsingDriverManager(getJDBCUrl("wombat",
urlAttributes + ";securityMechanism="
+ SECMEC_ATTRIBUTE[i]), "#");
// case - specify security mechanism on datasource
testSecurityMechanism(USER_ATTRIBUTE[k],PWD_ATTRIBUTE[j],
new Short(SECMEC_ATTRIBUTE[i]),"TEST_DS ("+urlAttributes+
",securityMechanism="+SECMEC_ATTRIBUTE[i]+")");
}
}
}
}
/**
* Helper method to get connection from datasource and to print
* the exceptions if any when getting a connection. This method
* is used in testAllCombinationsOfUserPasswordSecMecInput.
* For explanation of exceptions that might arise in this method,
* please check testAllCombinationsOfUserPasswordSecMecInput
* javadoc comment.
* get connection from datasource
* @param user username
* @param password password
* @param msg message to print for testcase
*/
public void getDataSourceConnection(String user, String password,String msg)
{
Connection conn;
try {
// get connection via datasource without setting securityMechanism
DataSource ds = getDS("wombat", user, password);
conn = ds.getConnection();
conn.close();
System.out.println(msg + " OK");
}
catch (SQLException sqle)
{
// Exceptions expected in certain case hence printing message
// instead of stack traces here.
// - For cases when userid is null or password is null and
// by default JCC does not allow a null password or null userid.
// - For case when JVM does not support EUSRIDPWD and JCC 2.6 tries
// to do autoswitching of security mechanism.
// - For case if server doesnt accept connection with this security
// mechanism
// - For case when client driver does support USRSSBPWD security
// mechanism
System.out.println(msg + "EXCEPTION getDataSourceConnection() " + sqle.getMessage());
dumpSQLException(sqle.getNextException());
}
catch (Exception e)
{
System.out.println("UNEXPECTED EXCEPTION!!!" + msg);
e.printStackTrace();
}
}
/**
* Dump SQLState and message for the complete nested chain of SQLException
* @param sqle SQLException whose complete chain of exceptions is
* traversed and sqlstate and message is printed out
*/
public static void dumpSQLException(SQLException sqle)
{
while ( sqle != null)
{
System.out.println("SQLSTATE("+sqle.getSQLState()+"): " + sqle.getMessage());
sqle = sqle.getNextException();
}
}
/**
* Test a deferred connection reset. When connection pooling is done
* and connection is reset, the client sends EXCSAT,ACCSEC and followed
* by SECCHK and ACCRDB. Test if the security mechanism related information
* is correctly reset or not. This method was added to help simulate regression
* test for DERBY-1080. It is called from testDerby1080
* @param user username
* @param password password for connection
* @param secmec security mechanism for datasource
* @throws Exception
*/
public void testSecMecWithConnPooling(String user, String password,
Short secmec) throws Exception
{
System.out.println("withConnectionPooling");
Connection conn;
String securityMechanismProperty = "SecurityMechanism";
Class[] argType = { Short.TYPE };
String methodName = TestUtil.getSetterName(securityMechanismProperty);
Object[] args = new Short[1];
args[0] = secmec;
ConnectionPoolDataSource cpds = getCPDS("wombat", user,password);
// call setSecurityMechanism with secmec.
Method sh = cpds.getClass().getMethod(methodName, argType);
sh.invoke(cpds, args);
// simulate case when connection will be re-used by getting
// a connection, closing it and then the next call to
// getConnection will re-use the previous connection.
PooledConnection pc = cpds.getPooledConnection();
conn = pc.getConnection();
conn.close();
conn = pc.getConnection();
test(conn);
conn.close();
System.out.println("OK");
}
/**
* Test a connection by executing a sample query
* @param conn database connection
* @throws Exception if there is any error
*/
public void test(Connection conn)
throws Exception
{
Statement stmt = null;
ResultSet rs = null;
try
{
// To test our connection, we will try to do a select from the system catalog tables
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from sys.systables");
while(rs.next())
System.out.println(" query ok ");
}
catch(SQLException sqle)
{
System.out.println("SQLException when querying on the database connection; "+ sqle);
throw sqle;
}
finally
{
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
}
}
/**
* This is a regression test for DERBY-1080 - where some variables required
* only for the EUSRIDPWD security mechanism case were not getting reset on
* connection re-use and resulting in protocol error. This also applies to
* USRSSBPWD security mechanism.
*
* Read class level comments (#1) to understand what is specified by drda
* spec for EUSRIDPWD.
* <br>
* Encryption is done using JCE. Hence JCE support of the necessary
* algorithm is required for EUSRIDPWD security mechanism to work. Thus
* even though the server and client have code to support EUSRIDPWD, this
* security mechanism will not work in all JVMs.
*
* JVMs where support for DH(32byte prime) is not available and thus EUSRIDPWD
* wont work are Sun JVM (versions 1.3.1,1.4.1,1.4.2,1.5) and
* IBM JVM (versions 1.3.1 and some old versions of 1.4.2 (in 2004) )
*
* Expected behavior for this test:
* If no regression has occurred, this test should work OK, given the
* expected exception in following cases:
* 1) When EUSRIDPWD is not supported in JVM the test is running, a CNFE
* with initializing EncryptionManager will happen. This will happen for
* Sun JVM (versions 1.3.1,1.4.1,1.4.2,1.5) and
* IBM JVM (versions 1.3.1 and some old versions of 1.4.2 (in 2004) )
* For JCC clients, error message is
* "java.lang.ClassNotFoundException is caught when initializing
* EncryptionManager 'IBMJCE'"
* For derby client, the error message is
* "Security exception encountered, see next exception for details."
* 2)If server does not accept EUSRIDPWD security mechanism from clients,then
* error message will be "Connection authorization failure
* occurred. Reason: security mechanism not supported"
* Note: #2 can happen if server is started with derby.drda.securityMechanism
* and thus restricts what security mechanisms the client can connect with.
* This will happen for the test run when derby.drda.securityMechanism is set and
* to some valid value other than ENCRYPTED_USER_AND_PASSWORD_SECURITY.
* <br>
* See RunTest where this method is called to test for regression for DERBY-1080.
* Also see main method to check if server is using the derby.drda.securityMechanism to
* restrict client connections based on security mechanism.
*/
public void testDerby1080()
{
try
{
System.out.println("Test DERBY-1080");
// simulate connection re-set using connection pooling on a pooled datasource
// set security mechanism to use encrypted userid and password.
testSecMecWithConnPooling("peter","neelima",new Short(SECMEC_EUSRIDPWD));
}
catch (SQLException sqle)
{
// Exceptions expected in certain case hence printing message instead of stack traces
// here.
// - For cases where the jvm does not support EUSRIDPWD.
// - For case if server doesnt accept connection with this security mechanism
// Please see javadoc comments for this test method for more details of expected
// exceptions.
System.out.println("DERBY-1080 EXCEPTION () " + sqle.getMessage());
dumpSQLException(sqle.getNextException());
}
catch (Exception e)
{
System.out.println("UNEXPECTED EXCEPTION!!!" );
e.printStackTrace();
}
}
/**
* Test SECMEC_USRSSBPWD with derby BUILTIN authentication turned ON.
*
* We want to test a combination of USRSSBPWD with BUILTIN as password
* substitute is only supported with NONE or BUILTIN Derby authentication
* scheme right now (DERBY-528).
*
* @throws Exception if there an unexpected error
*/
public void testUSRSSBPWD_with_BUILTIN()
{
// Turn on Derby BUILTIN authentication and attempt connecting
// with USRSSBPWD security mechanism.
System.out.println(
"Test USRSSBPWD_with_BUILTIN - derby.drda.securityMechanism=" +
System.getProperty("derby.drda.securityMechanism"));
try
{
System.out.println("Turning ON Derby BUILTIN authentication");
Connection conn =
getConnectionWithSecMec("neelima", "lee",
new Short(SECMEC_USRSSBPWD));
if (conn == null)
return; // Exception would have been raised
// Turn on BUILTIN authentication
CallableStatement cs =
conn.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
cs.setString(1, "derby.user.neelima");
cs.setString(2, "lee");
cs.execute();
cs.setString(1, "derby.connection.requireAuthentication");
cs.setString(2, "true");
cs.execute();
cs.close();
cs = null;
conn.close();
// Shutdown 'wombat' database for BUILTIN
// authentication to take effect the next time it is
// booted - derby.connection.requireAuthentication is a
// static property.
getConnectionUsingDriverManager(getJDBCUrl(
"wombat","user=neelima;password=lee;shutdown=true;securityMechanism=" +
SECMEC_USRSSBPWD),"USRSSBPWD (T0):");
// Now test some connection(s) with SECMEC_USRSSBPWD
// via DriverManager and Datasource
getConnectionUsingDriverManager(getJDBCUrl(
"wombat","user=neelima;password=lee;securityMechanism=" +
SECMEC_USRSSBPWD),"USRSSBPWD + BUILTIN (T1):");
testSecurityMechanism("neelima","lee",new Short(SECMEC_USRSSBPWD),
"TEST_DS - USRSSBPWD + BUILTIN (T2):");
// Attempting to connect with some invalid user
getConnectionUsingDriverManager(getJDBCUrl(
"wombat","user=invalid;password=user;securityMechanism=" +
SECMEC_USRSSBPWD),"USRSSBPWD + BUILTIN (T3):");
testSecurityMechanism("invalid","user",new Short(SECMEC_USRSSBPWD),
"TEST_DS - USRSSBPWD + BUILTIN (T4):");
System.out.println("Turning OFF Derby BUILTIN authentication");
conn = getConnectionWithSecMec("neelima", "lee",
new Short(SECMEC_USRSSBPWD));
if (conn == null)
return; // Exception would have been raised
// Turn off BUILTIN authentication
cs = conn.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
cs.setString(1, "derby.connection.requireAuthentication");
cs.setString(2, "false");
cs.execute();
cs.close();
cs = null;
conn.close();
// Shutdown 'wombat' database for BUILTIN authentication
// to take effect the next time it is booted
getConnectionUsingDriverManager(getJDBCUrl(
"wombat","user=neelima;password=lee;shutdown=true;securityMechanism=" +
SECMEC_USRSSBPWD),"USRSSBPWD + BUILTIN (T5):");
}
catch (Exception e)
{
System.out.println(
"FAIL: testUSRSSBPWD_with_BUILTIN(). Unexpected Exception " +
e.getMessage());
e.printStackTrace();
}
}
public Connection getConnectionWithSecMec(String user,
String password,
Short secMec)
{
Connection conn = null;
String securityMechanismProperty = "SecurityMechanism";
Class[] argType = { Short.TYPE };
String methodName = TestUtil.getSetterName(securityMechanismProperty);
Object[] args = new Short[1];
args[0] = secMec;
try {
DataSource ds = getDS("wombat", user, password);
Method sh = ds.getClass().getMethod(methodName, argType);
sh.invoke(ds, args);
conn = ds.getConnection();
}
catch (SQLException sqle)
{
// Exceptions expected in certain cases depending on JCE used for
// running the test. hence printing message instead of stack traces
// here.
System.out.println("EXCEPTION getConnectionWithSecMec() " + sqle.getMessage());
dumpSQLException(sqle.getNextException());
}
catch (Exception e)
{
System.out.println(
"UNEXPECTED EXCEPTION!!! getConnectionWithSecMec() - " +
secMec);
e.printStackTrace();
}
return conn;
}
}
| true | true | public static void main(String[] args) throws Exception {
// Load harness properties.
ij.getPropertyArg(args);
String hostName = TestUtil.getHostName();
if (hostName.equals("localhost"))
NETWORKSERVER_PORT = 20000;
else
NETWORKSERVER_PORT = 1527;
// "runTest()" is going to try to connect to the database through
// the server at port NETWORKSERVER_PORT. Thus, we have to
// start the server on that port before calling runTest.
try {
TestUtil.loadDriver();
} catch (Exception e) {
e.printStackTrace();
}
PrintStream originalStream = System.out;
FileOutputStream shutdownLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.std.log");
SwitchablePrintStream consoleLogStream =
new SwitchablePrintStream( originalStream );
PrintStream originalErrStream = System.err;
FileOutputStream shutdownErrLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.err.log");
SwitchablePrintStream consoleErrLogStream =
new SwitchablePrintStream( originalErrStream );
System.setOut( consoleLogStream );
System.setErr( consoleErrLogStream );
// Start server with a specific value for derby.drda.securityMechanism
// and run tests. Note connections will be successful or not depending on
// derby.drda.securityMechanism property specified on the server (DERBY-928)
// @see
// org.apache.derby.iapi.reference.Property#DRDA_PROP_SECURITYMECHANISM
for ( int i = 0; i < derby_drda_securityMechanism.length; i++)
{
if (derby_drda_securityMechanism[i]!=null)
System.setProperty("derby.drda.securityMechanism",derby_drda_securityMechanism[i]);
System.out.println("----------------------------------------------");
System.out.println("Testing with derby.drda.securityMechanism="+
System.getProperty("derby.drda.securityMechanism"));
// Start the NetworkServer on another thread, unless it's a remote host
if (hostName.equals("localhost"))
{
try
{
networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT);
networkServer.start(null);
}catch(Exception e)
{
if ( derby_drda_securityMechanism[i].equals("INVALID_VALUE")||
derby_drda_securityMechanism[i].equals(""))
{
System.out.println("EXPECTED EXCEPTION "+ e.getMessage());
continue;
}
}
// Wait for the NetworkServer to start.
if (!isServerStarted(networkServer, 60))
System.exit(-1);
}
// Now, go ahead and run the test.
try {
testSecMec tester =
new testSecMec(consoleLogStream,
originalStream,
shutdownLogStream,
consoleErrLogStream,
originalErrStream,
shutdownErrLogStream);
// Now run the test, note connections will be successful or
// throw an exception depending on derby.drda.securityMechanism
// property specified on the server
tester.runTest();
} catch (Exception e) {
// if we catch an exception of some sort, we need to make sure to
// close our streams before returning; otherwise, we can get
// hangs in the harness. SO, catching all exceptions here keeps
// us from exiting before closing the necessary streams.
System.out.println("FAIL - Exiting due to unexpected error: " +
e.getMessage());
e.printStackTrace();
}
// Shutdown the server.
if (hostName.equals("localhost"))
{
consoleLogStream.switchOutput( shutdownLogStream );
consoleErrLogStream.switchOutput( shutdownErrLogStream );
networkServer.shutdown();
consoleLogStream.flush();
// how do we do this with the new api?
//networkServer.join();
Thread.sleep(5000);
consoleLogStream.switchOutput( originalStream );
consoleErrLogStream.switchOutput( originalErrStream );
}
// Now we want to test
}
System.out.println("Completed testSecMec");
originalStream.close();
shutdownLogStream.close();
originalErrStream.close();
shutdownErrLogStream.close();
}
| public static void main(String[] args) throws Exception {
// Load harness properties.
ij.getPropertyArg(args);
String hostName = TestUtil.getHostName();
if (hostName.equals("localhost"))
NETWORKSERVER_PORT = 20000;
else
NETWORKSERVER_PORT = 1527;
// "runTest()" is going to try to connect to the database through
// the server at port NETWORKSERVER_PORT. Thus, we have to
// start the server on that port before calling runTest.
try {
TestUtil.loadDriver();
} catch (Exception e) {
e.printStackTrace();
}
PrintStream originalStream = System.out;
FileOutputStream shutdownLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.std.log");
SwitchablePrintStream consoleLogStream =
new SwitchablePrintStream( originalStream );
PrintStream originalErrStream = System.err;
FileOutputStream shutdownErrLogStream =
new FileOutputStream("testSecMec." +
System.getProperty("framework","") + "." +
"shutdown.err.log");
SwitchablePrintStream consoleErrLogStream =
new SwitchablePrintStream( originalErrStream );
System.setOut( consoleLogStream );
System.setErr( consoleErrLogStream );
// Start server with a specific value for derby.drda.securityMechanism
// and run tests. Note connections will be successful or not depending on
// derby.drda.securityMechanism property specified on the server (DERBY-928)
// @see
// org.apache.derby.iapi.reference.Property#DRDA_PROP_SECURITYMECHANISM
for ( int i = 0; i < derby_drda_securityMechanism.length; i++)
{
if (derby_drda_securityMechanism[i]!=null)
System.setProperty("derby.drda.securityMechanism",derby_drda_securityMechanism[i]);
System.out.println("----------------------------------------------");
System.out.println("Testing with derby.drda.securityMechanism="+
System.getProperty("derby.drda.securityMechanism"));
// Start the NetworkServer on another thread, unless it's a remote host
if (hostName.equals("localhost"))
{
try
{
networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT);
networkServer.start(null);
}catch(Exception e)
{
if ( derby_drda_securityMechanism[i].equals("INVALID_VALUE")||
derby_drda_securityMechanism[i].equals(""))
{
System.out.println("EXPECTED EXCEPTION "+ e.getMessage());
continue;
}
}
// Wait for the NetworkServer to start.
if (!isServerStarted(networkServer, 60)) {
System.out.println("FAIL: Server failed to respond to ping - ending test");
break;
}
}
// Now, go ahead and run the test.
try {
testSecMec tester =
new testSecMec(consoleLogStream,
originalStream,
shutdownLogStream,
consoleErrLogStream,
originalErrStream,
shutdownErrLogStream);
// Now run the test, note connections will be successful or
// throw an exception depending on derby.drda.securityMechanism
// property specified on the server
tester.runTest();
} catch (Exception e) {
// if we catch an exception of some sort, we need to make sure to
// close our streams before returning; otherwise, we can get
// hangs in the harness. SO, catching all exceptions here keeps
// us from exiting before closing the necessary streams.
System.out.println("FAIL - Exiting due to unexpected error: " +
e.getMessage());
e.printStackTrace();
}
// Shutdown the server.
if (hostName.equals("localhost"))
{
consoleLogStream.switchOutput( shutdownLogStream );
consoleErrLogStream.switchOutput( shutdownErrLogStream );
networkServer.shutdown();
consoleLogStream.flush();
// how do we do this with the new api?
//networkServer.join();
Thread.sleep(5000);
consoleLogStream.switchOutput( originalStream );
consoleErrLogStream.switchOutput( originalErrStream );
}
// Now we want to test
}
System.out.println("Completed testSecMec");
originalStream.close();
shutdownLogStream.close();
originalErrStream.close();
shutdownErrLogStream.close();
}
|
diff --git a/src/org/encog/workbench/frames/document/EncogPopupMenus.java b/src/org/encog/workbench/frames/document/EncogPopupMenus.java
index af28cfc2..91a7e298 100644
--- a/src/org/encog/workbench/frames/document/EncogPopupMenus.java
+++ b/src/org/encog/workbench/frames/document/EncogPopupMenus.java
@@ -1,256 +1,256 @@
/*
* Encog(tm) Workbench v2.6
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2010 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.workbench.frames.document;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.encog.persist.DirectoryEntry;
import org.encog.persist.EncogPersistedCollection;
import org.encog.util.file.FileUtil;
import org.encog.workbench.EncogWorkBench;
import org.encog.workbench.frames.document.tree.ProjectDirectory;
import org.encog.workbench.frames.document.tree.ProjectEGItem;
import org.encog.workbench.frames.document.tree.ProjectFile;
import org.encog.workbench.frames.document.tree.ProjectItem;
import org.encog.workbench.process.CreateNewFile;
import org.encog.workbench.process.EncogAnalystWizard;
import org.encog.workbench.process.ImportExport;
public class EncogPopupMenus {
private JPopupMenu popupNetwork;
private JMenuItem popupNetworkDelete;
private JMenuItem popupNetworkProperties;
private JMenuItem popupNetworkOpen;
private JMenuItem popupNetworkQuery;
private JPopupMenu popupData;
private JMenuItem popupDataDelete;
private JMenuItem popupDataProperties;
private JMenuItem popupDataOpen;
private JMenuItem popupDataExport;
private JPopupMenu popupGeneral;
private JMenuItem popupGeneralOpen;
private JMenuItem popupGeneralDelete;
private JMenuItem popupGeneralProperties;
private EncogDocumentFrame owner;
private JPopupMenu popupFile;
private JMenuItem popupFileDelete;
private JMenuItem popupFileOpen;
private JMenuItem popupFileOpenText;
private JMenuItem popupFileRefresh;
private JPopupMenu popupFileCSV;
private JMenuItem popupFileCSVDelete;
private JMenuItem popupFileCSVOpen;
private JMenuItem popupFileCSVRefresh;
private JMenuItem popupFileCSVExport;
private JMenuItem popupFileCSVWizard;
private JPopupMenu popupRefresh;
private JMenuItem popupRefreshItem;
private JPopupMenu popupRoot;
private JMenuItem popupRootRefreshItem;
private JMenuItem popupRootNewFile;
public EncogPopupMenus(EncogDocumentFrame owner) {
this.owner = owner;
}
void initPopup() {
// build network popup menu
this.popupNetwork = new JPopupMenu();
this.popupNetworkDelete = owner.addItem(this.popupNetwork, "Delete",
'd');
this.popupNetworkOpen = owner.addItem(this.popupNetwork, "Open", 'o');
this.popupNetworkProperties = owner.addItem(this.popupNetwork,
"Properties", 'p');
this.popupNetworkQuery = owner.addItem(this.popupNetwork, "Query", 'q');
this.popupData = new JPopupMenu();
this.popupDataDelete = owner.addItem(this.popupData, "Delete", 'd');
this.popupDataOpen = owner.addItem(this.popupData, "Open", 'o');
this.popupDataProperties = owner.addItem(this.popupData, "Properties",
'p');
this.popupDataExport = owner.addItem(this.popupData, "Export...", 'e');
this.popupGeneral = new JPopupMenu();
this.popupGeneralDelete = owner.addItem(this.popupGeneral, "Delete",
'd');
this.popupGeneralOpen = owner.addItem(this.popupGeneral, "Open", 'o');
this.popupGeneralProperties = owner.addItem(this.popupGeneral,
"Properties", 'p');
this.popupFile = new JPopupMenu();
this.popupFileOpen = owner.addItem(this.popupFile, "Open", 'o');
this.popupFileOpenText = owner.addItem(this.popupFile, "Open as Text",
't');
this.popupFileDelete = owner.addItem(this.popupFile, "Delete", 'd');
this.popupFileRefresh = owner.addItem(this.popupFile, "Refresh", 'r');
this.popupRefresh = new JPopupMenu();
this.popupRefreshItem = owner
.addItem(this.popupRefresh, "Refresh", 'r');
this.popupFileCSV = new JPopupMenu();
this.popupFileCSVOpen = owner.addItem(this.popupFileCSV, "Open", 'o');
this.popupFileCSVDelete = owner.addItem(this.popupFileCSV, "Delete",
'd');
this.popupFileCSVRefresh = owner.addItem(this.popupFileCSV, "Refresh",
'r');
this.popupFileCSVExport = owner.addItem(this.popupFileCSV,
"Export to Training(EGB)", 'x');
this.popupFileCSVWizard = owner.addItem(this.popupFileCSV,
"Analyst Wizard...", 'w');
this.popupRoot = new JPopupMenu();
this.popupRootRefreshItem = owner
.addItem(this.popupRoot, "Refresh", 'r');
this.popupRootNewFile = owner
.addItem(this.popupRoot, "New File", 'n');
}
public void actionPerformed(final ActionEvent event) {
performPopupMenu(event.getSource());
}
public void performPopupMenu(final Object source) {
if (source == this.popupFileRefresh || source == this.popupRefreshItem
|| source == this.popupFileCSVRefresh || source==popupRootRefreshItem) {
EncogWorkBench.getInstance().getMainWindow().getTree().refresh();
}
else if (source == this.popupRootNewFile ) {
try {
CreateNewFile.performCreateFile();
} catch (IOException e) {
EncogWorkBench.displayError("Error", e);
}
}
boolean first = true;
List<ProjectItem> list = this.owner.getTree().getSelectedValue();
if (list == null)
return;
for (ProjectItem selected : list) {
- if (source == this.popupFileDelete) {
+ if (source == this.popupFileDelete || source==this.popupFileCSVDelete || source==this.popupDataDelete || source==this.popupGeneralDelete ) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these file(s)?")) {
return;
}
first = false;
if (selected instanceof ProjectFile) {
((ProjectFile) selected).getFile().delete();
}
EncogWorkBench.getInstance().getMainWindow().getTree()
.refresh();
} else if (source == this.popupFileOpen
|| source == this.popupFileCSVOpen) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openFile(((ProjectFile) selected).getFile());
}
} else if (source == this.popupFileOpenText) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openTextFile(((ProjectFile) selected).getFile());
}
} else if ((source == this.popupNetworkDelete)
|| (source == this.popupDataDelete)
|| (source == this.popupGeneralDelete)
|| (source == this.popupFileCSVDelete)) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these object(s)?")) {
return;
}
owner.getOperations().performObjectsDelete(selected);
} else if (source == this.popupFileCSVExport) {
String sourceFile = ((ProjectFile) selected).getFile()
.toString();
String targetFile = FileUtil.forceExtension(sourceFile, "egb");
ImportExport.performExternal2Bin(new File(sourceFile),
new File(targetFile), null);
} else if (source == this.popupFileCSVWizard) {
File sourceFile = ((ProjectFile) selected).getFile();
EncogAnalystWizard.createEncogAnalyst(sourceFile);
}
first = false;
}
}
public void rightMouseClicked(final MouseEvent e, final Object item) {
if (item instanceof DirectoryEntry) {
DirectoryEntry entry = (DirectoryEntry) item;
if (EncogPersistedCollection.TYPE_BASIC_NET.equals(entry.getType())) {
this.popupNetwork.show(e.getComponent(), e.getX(), e.getY());
} else if (EncogPersistedCollection.TYPE_BASIC_NET.equals(entry
.getType())) {
this.popupData.show(e.getComponent(), e.getX(), e.getY());
} else {
this.popupGeneral.show(e.getComponent(), e.getX(), e.getY());
}
} else if (item instanceof ProjectFile) {
ProjectFile file = (ProjectFile) item;
if (file.getExtension().equalsIgnoreCase("csv")) {
this.popupFileCSV.show(e.getComponent(), e.getX(), e.getY());
} else {
this.popupFile.show(e.getComponent(), e.getX(), e.getY());
}
} else if (item instanceof ProjectEGItem) {
this.popupGeneral.show(e.getComponent(), e.getX(), e.getY());
} else if (item instanceof String) {
this.popupRoot.show(e.getComponent(), e.getX(), e.getY());
} else {
this.popupRefresh.show(e.getComponent(), e.getX(), e.getY());
}
}
public void performPopupDelete() {
this.performPopupMenu(this.popupNetworkDelete);
}
}
| true | true | public void performPopupMenu(final Object source) {
if (source == this.popupFileRefresh || source == this.popupRefreshItem
|| source == this.popupFileCSVRefresh || source==popupRootRefreshItem) {
EncogWorkBench.getInstance().getMainWindow().getTree().refresh();
}
else if (source == this.popupRootNewFile ) {
try {
CreateNewFile.performCreateFile();
} catch (IOException e) {
EncogWorkBench.displayError("Error", e);
}
}
boolean first = true;
List<ProjectItem> list = this.owner.getTree().getSelectedValue();
if (list == null)
return;
for (ProjectItem selected : list) {
if (source == this.popupFileDelete) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these file(s)?")) {
return;
}
first = false;
if (selected instanceof ProjectFile) {
((ProjectFile) selected).getFile().delete();
}
EncogWorkBench.getInstance().getMainWindow().getTree()
.refresh();
} else if (source == this.popupFileOpen
|| source == this.popupFileCSVOpen) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openFile(((ProjectFile) selected).getFile());
}
} else if (source == this.popupFileOpenText) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openTextFile(((ProjectFile) selected).getFile());
}
} else if ((source == this.popupNetworkDelete)
|| (source == this.popupDataDelete)
|| (source == this.popupGeneralDelete)
|| (source == this.popupFileCSVDelete)) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these object(s)?")) {
return;
}
owner.getOperations().performObjectsDelete(selected);
} else if (source == this.popupFileCSVExport) {
String sourceFile = ((ProjectFile) selected).getFile()
.toString();
String targetFile = FileUtil.forceExtension(sourceFile, "egb");
ImportExport.performExternal2Bin(new File(sourceFile),
new File(targetFile), null);
} else if (source == this.popupFileCSVWizard) {
File sourceFile = ((ProjectFile) selected).getFile();
EncogAnalystWizard.createEncogAnalyst(sourceFile);
}
first = false;
}
}
| public void performPopupMenu(final Object source) {
if (source == this.popupFileRefresh || source == this.popupRefreshItem
|| source == this.popupFileCSVRefresh || source==popupRootRefreshItem) {
EncogWorkBench.getInstance().getMainWindow().getTree().refresh();
}
else if (source == this.popupRootNewFile ) {
try {
CreateNewFile.performCreateFile();
} catch (IOException e) {
EncogWorkBench.displayError("Error", e);
}
}
boolean first = true;
List<ProjectItem> list = this.owner.getTree().getSelectedValue();
if (list == null)
return;
for (ProjectItem selected : list) {
if (source == this.popupFileDelete || source==this.popupFileCSVDelete || source==this.popupDataDelete || source==this.popupGeneralDelete ) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these file(s)?")) {
return;
}
first = false;
if (selected instanceof ProjectFile) {
((ProjectFile) selected).getFile().delete();
}
EncogWorkBench.getInstance().getMainWindow().getTree()
.refresh();
} else if (source == this.popupFileOpen
|| source == this.popupFileCSVOpen) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openFile(((ProjectFile) selected).getFile());
}
} else if (source == this.popupFileOpenText) {
if (selected instanceof ProjectFile) {
EncogWorkBench.getInstance().getMainWindow()
.openTextFile(((ProjectFile) selected).getFile());
}
} else if ((source == this.popupNetworkDelete)
|| (source == this.popupDataDelete)
|| (source == this.popupGeneralDelete)
|| (source == this.popupFileCSVDelete)) {
if (first
&& !EncogWorkBench
.askQuestion("Warning",
"Are you sure you want to delete these object(s)?")) {
return;
}
owner.getOperations().performObjectsDelete(selected);
} else if (source == this.popupFileCSVExport) {
String sourceFile = ((ProjectFile) selected).getFile()
.toString();
String targetFile = FileUtil.forceExtension(sourceFile, "egb");
ImportExport.performExternal2Bin(new File(sourceFile),
new File(targetFile), null);
} else if (source == this.popupFileCSVWizard) {
File sourceFile = ((ProjectFile) selected).getFile();
EncogAnalystWizard.createEncogAnalyst(sourceFile);
}
first = false;
}
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/map/MapProxy.java b/hazelcast/src/main/java/com/hazelcast/map/MapProxy.java
index 3601a5849f..9e3b855514 100644
--- a/hazelcast/src/main/java/com/hazelcast/map/MapProxy.java
+++ b/hazelcast/src/main/java/com/hazelcast/map/MapProxy.java
@@ -1,197 +1,200 @@
/*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* 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.hazelcast.map;
import com.hazelcast.core.Transaction;
import com.hazelcast.spi.ServiceProxy;
import com.hazelcast.transaction.TransactionImpl;
import com.hazelcast.spi.Invocation;
import com.hazelcast.spi.NodeService;
import com.hazelcast.spi.impl.Response;
import com.hazelcast.nio.Data;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.map.MapService.MAP_SERVICE_NAME;
import static com.hazelcast.nio.IOUtil.toData;
import static com.hazelcast.nio.IOUtil.toObject;
public class MapProxy implements ServiceProxy {
private final NodeService nodeService;
private final MapService mapService;
public MapProxy(final MapService mapService, NodeService nodeService) {
this.mapService = mapService;
this.nodeService = nodeService;
}
public Object remove(String name, Object k) {
Data key = nodeService.toData(k);
int partitionId = nodeService.getPartitionId(key);
TransactionImpl txn = nodeService.getTransaction();
String txnId = null;
if (txn != null && txn.getStatus() == Transaction.TXN_STATUS_ACTIVE) {
txnId = txn.getTxnId();
txn.attachParticipant(MAP_SERVICE_NAME, partitionId);
}
RemoveOperation removeOperation = new RemoveOperation(name, toData(k), txnId);
removeOperation.setValidateTarget(true);
long backupCallId = mapService.createNewBackupCallQueue();
try {
removeOperation.setBackupCallId(backupCallId);
removeOperation.setServiceName(MAP_SERVICE_NAME);
Invocation invocation = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, removeOperation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = null;
if (response instanceof Response) {
Response r = (Response) response;
returnObj = r.getResult();
} else {
returnObj = toObject(response);
}
+ if (returnObj == null) {
+ return null;
+ }
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
UpdateResponse updateResponse = (UpdateResponse) returnObj;
int backupCount = updateResponse.getBackupCount();
if (backupCount > 0) {
boolean backupsComplete = true;
for (int i = 0; i < backupCount; i++) {
BlockingQueue backupResponses = mapService.getBackupCallQueue(backupCallId);
Object backupResponse = backupResponses.poll(3, TimeUnit.SECONDS);
if (backupResponse == null) {
backupsComplete = false;
}
}
if (!backupsComplete) {
for (int i = 0; i < backupCount; i++) {
Data dataValue = removeOperation.getValue();
GenericBackupOperation backupOp = new GenericBackupOperation(name, key, dataValue, -1, updateResponse.getVersion());
backupOp.setBackupOpType(GenericBackupOperation.BackupOpType.REMOVE);
backupOp.setInvocation(true);
Invocation backupInv = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, backupOp,
partitionId).setReplicaIndex(i).build();
f = backupInv.invoke();
f.get(5, TimeUnit.SECONDS);
}
}
}
return toObject(updateResponse.getOldValue());
} catch (Throwable throwable) {
throw (RuntimeException) throwable;
} finally {
mapService.removeBackupCallQueue(backupCallId);
}
}
public Object put(String name, Object k, Object v, long ttl) {
Data key = nodeService.toData(k);
int partitionId = nodeService.getPartitionId(key);
TransactionImpl txn = nodeService.getTransaction();
String txnId = null;
if (txn != null && txn.getStatus() == Transaction.TXN_STATUS_ACTIVE) {
txnId = txn.getTxnId();
txn.attachParticipant(MAP_SERVICE_NAME, partitionId);
}
PutOperation putOperation = new PutOperation(name, toData(k), v, txnId, ttl);
putOperation.setValidateTarget(true);
long backupCallId = mapService.createNewBackupCallQueue();
try {
putOperation.setBackupCallId(backupCallId);
putOperation.setServiceName(MAP_SERVICE_NAME);
Invocation invocation = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, putOperation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = null;
if (response instanceof Response) {
Response r = (Response) response;
returnObj = r.getResult();
} else {
returnObj = toObject(response);
}
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
UpdateResponse updateResponse = (UpdateResponse) returnObj;
int backupCount = updateResponse.getBackupCount();
if (backupCount > 0) {
boolean backupsComplete = true;
for (int i = 0; i < backupCount; i++) {
BlockingQueue backupResponses = mapService.getBackupCallQueue(backupCallId);
Object backupResponse = backupResponses.poll(3, TimeUnit.SECONDS);
if (backupResponse == null) {
backupsComplete = false;
}
}
if (!backupsComplete) {
for (int i = 0; i < backupCount; i++) {
Data dataValue = putOperation.getValue();
GenericBackupOperation backupOp = new GenericBackupOperation(name, key, dataValue, ttl, updateResponse.getVersion());
backupOp.setInvocation(true);
Invocation backupInv = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, backupOp,
partitionId).setReplicaIndex(i).build();
f = backupInv.invoke();
f.get(5, TimeUnit.SECONDS);
}
}
}
return toObject(updateResponse.getOldValue());
} catch (Throwable throwable) {
throw (RuntimeException) throwable;
} finally {
mapService.removeBackupCallQueue(backupCallId);
}
}
public Object getOperation(String name, Object k) {
Data key = nodeService.toData(k);
int partitionId = nodeService.getPartitionId(key);
GetOperation getOperation = new GetOperation(name, toData(k));
getOperation.setValidateTarget(true);
getOperation.setServiceName(MAP_SERVICE_NAME);
try {
Invocation invocation = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, getOperation, partitionId).build();
Future f = invocation.invoke();
Data response = (Data) f.get();
return toObject(response);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
public int getSize(String name) {
try {
MapSizeOperation mapSizeOperation = new MapSizeOperation(name);
mapSizeOperation.setValidateTarget(true);
Map<Integer, Object> results = nodeService.invokeOnAllPartitions(MAP_SERVICE_NAME, mapSizeOperation);
int total = 0;
for (Object result : results.values()) {
Integer size = (Integer) nodeService.toObject(result);
total += size;
}
return total;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
| true | true | public Object remove(String name, Object k) {
Data key = nodeService.toData(k);
int partitionId = nodeService.getPartitionId(key);
TransactionImpl txn = nodeService.getTransaction();
String txnId = null;
if (txn != null && txn.getStatus() == Transaction.TXN_STATUS_ACTIVE) {
txnId = txn.getTxnId();
txn.attachParticipant(MAP_SERVICE_NAME, partitionId);
}
RemoveOperation removeOperation = new RemoveOperation(name, toData(k), txnId);
removeOperation.setValidateTarget(true);
long backupCallId = mapService.createNewBackupCallQueue();
try {
removeOperation.setBackupCallId(backupCallId);
removeOperation.setServiceName(MAP_SERVICE_NAME);
Invocation invocation = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, removeOperation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = null;
if (response instanceof Response) {
Response r = (Response) response;
returnObj = r.getResult();
} else {
returnObj = toObject(response);
}
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
UpdateResponse updateResponse = (UpdateResponse) returnObj;
int backupCount = updateResponse.getBackupCount();
if (backupCount > 0) {
boolean backupsComplete = true;
for (int i = 0; i < backupCount; i++) {
BlockingQueue backupResponses = mapService.getBackupCallQueue(backupCallId);
Object backupResponse = backupResponses.poll(3, TimeUnit.SECONDS);
if (backupResponse == null) {
backupsComplete = false;
}
}
if (!backupsComplete) {
for (int i = 0; i < backupCount; i++) {
Data dataValue = removeOperation.getValue();
GenericBackupOperation backupOp = new GenericBackupOperation(name, key, dataValue, -1, updateResponse.getVersion());
backupOp.setBackupOpType(GenericBackupOperation.BackupOpType.REMOVE);
backupOp.setInvocation(true);
Invocation backupInv = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, backupOp,
partitionId).setReplicaIndex(i).build();
f = backupInv.invoke();
f.get(5, TimeUnit.SECONDS);
}
}
}
return toObject(updateResponse.getOldValue());
} catch (Throwable throwable) {
throw (RuntimeException) throwable;
} finally {
mapService.removeBackupCallQueue(backupCallId);
}
}
| public Object remove(String name, Object k) {
Data key = nodeService.toData(k);
int partitionId = nodeService.getPartitionId(key);
TransactionImpl txn = nodeService.getTransaction();
String txnId = null;
if (txn != null && txn.getStatus() == Transaction.TXN_STATUS_ACTIVE) {
txnId = txn.getTxnId();
txn.attachParticipant(MAP_SERVICE_NAME, partitionId);
}
RemoveOperation removeOperation = new RemoveOperation(name, toData(k), txnId);
removeOperation.setValidateTarget(true);
long backupCallId = mapService.createNewBackupCallQueue();
try {
removeOperation.setBackupCallId(backupCallId);
removeOperation.setServiceName(MAP_SERVICE_NAME);
Invocation invocation = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, removeOperation, partitionId).build();
Future f = invocation.invoke();
Object response = f.get();
Object returnObj = null;
if (response instanceof Response) {
Response r = (Response) response;
returnObj = r.getResult();
} else {
returnObj = toObject(response);
}
if (returnObj == null) {
return null;
}
if (returnObj instanceof Throwable) {
throw (Throwable) returnObj;
}
UpdateResponse updateResponse = (UpdateResponse) returnObj;
int backupCount = updateResponse.getBackupCount();
if (backupCount > 0) {
boolean backupsComplete = true;
for (int i = 0; i < backupCount; i++) {
BlockingQueue backupResponses = mapService.getBackupCallQueue(backupCallId);
Object backupResponse = backupResponses.poll(3, TimeUnit.SECONDS);
if (backupResponse == null) {
backupsComplete = false;
}
}
if (!backupsComplete) {
for (int i = 0; i < backupCount; i++) {
Data dataValue = removeOperation.getValue();
GenericBackupOperation backupOp = new GenericBackupOperation(name, key, dataValue, -1, updateResponse.getVersion());
backupOp.setBackupOpType(GenericBackupOperation.BackupOpType.REMOVE);
backupOp.setInvocation(true);
Invocation backupInv = nodeService.createInvocationBuilder(MAP_SERVICE_NAME, backupOp,
partitionId).setReplicaIndex(i).build();
f = backupInv.invoke();
f.get(5, TimeUnit.SECONDS);
}
}
}
return toObject(updateResponse.getOldValue());
} catch (Throwable throwable) {
throw (RuntimeException) throwable;
} finally {
mapService.removeBackupCallQueue(backupCallId);
}
}
|
diff --git a/src/src/com/zachklipp/captivate/Application.java b/src/src/com/zachklipp/captivate/Application.java
index bc84704..8b74aec 100644
--- a/src/src/com/zachklipp/captivate/Application.java
+++ b/src/src/com/zachklipp/captivate/Application.java
@@ -1,27 +1,30 @@
package com.zachklipp.captivate;
import com.zachklipp.captivate.util.Log;
public class Application extends android.app.Application
{
@Override
public void onCreate()
{
initializeLogging();
}
private void initializeLogging()
{
Log.setDefaultTag("captivate");
+ /* NOTE: Due to an ADT bug, Project -> Build Automatically must be unchecked for
+ * this to take effect.
+ */
if (!BuildConfig.DEBUG)
{
Log.v("Configured for release, disabling debug logging");
Log.setMinPriority(android.util.Log.INFO);
}
else
{
Log.v("Configured for dev, enabling debug logging");
}
}
}
| true | true | private void initializeLogging()
{
Log.setDefaultTag("captivate");
if (!BuildConfig.DEBUG)
{
Log.v("Configured for release, disabling debug logging");
Log.setMinPriority(android.util.Log.INFO);
}
else
{
Log.v("Configured for dev, enabling debug logging");
}
}
| private void initializeLogging()
{
Log.setDefaultTag("captivate");
/* NOTE: Due to an ADT bug, Project -> Build Automatically must be unchecked for
* this to take effect.
*/
if (!BuildConfig.DEBUG)
{
Log.v("Configured for release, disabling debug logging");
Log.setMinPriority(android.util.Log.INFO);
}
else
{
Log.v("Configured for dev, enabling debug logging");
}
}
|
diff --git a/anadix-api/src/main/java/org/analyzer/factories/StringSource.java b/anadix-api/src/main/java/org/analyzer/factories/StringSource.java
index 8f63f96..77a5dff 100755
--- a/anadix-api/src/main/java/org/analyzer/factories/StringSource.java
+++ b/anadix-api/src/main/java/org/analyzer/factories/StringSource.java
@@ -1,54 +1,57 @@
/*
* Copyright 2011 Tomas Schlosser
*
* 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.analyzer.factories;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import org.analyzer.Source;
class StringSource implements Source {
private final String source;
private final String description;
public StringSource(String source) {
this(source, null);
}
public StringSource(String source, String description) {
+ if (source == null) {
+ throw new NullPointerException("source can't be null");
+ }
this.source = source;
this.description = description;
}
public String getDescription() {
return description;
}
public String getText() {
return source;
}
public Reader getReader() {
return new StringReader(source);
}
public InputStream getStream() {
return new ByteArrayInputStream(source.getBytes());
}
}
| true | true | public StringSource(String source, String description) {
this.source = source;
this.description = description;
}
| public StringSource(String source, String description) {
if (source == null) {
throw new NullPointerException("source can't be null");
}
this.source = source;
this.description = description;
}
|
diff --git a/src/net/java/sip/communicator/impl/gui/main/chatroomslist/ChatRoomsList.java b/src/net/java/sip/communicator/impl/gui/main/chatroomslist/ChatRoomsList.java
index a7bc6763c..a3541fa3b 100644
--- a/src/net/java/sip/communicator/impl/gui/main/chatroomslist/ChatRoomsList.java
+++ b/src/net/java/sip/communicator/impl/gui/main/chatroomslist/ChatRoomsList.java
@@ -1,364 +1,364 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.chatroomslist;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.chat.*;
import net.java.sip.communicator.impl.gui.main.chat.conference.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
/**
* The <tt>ChatRoomsList</tt> is the list containing all chat rooms.
*
* @author Yana Stamcheva
*/
public class ChatRoomsList
extends JList
implements MouseListener
{
private Logger logger = Logger.getLogger(ChatRoomsList.class);
private MainFrame mainFrame;
private DefaultListModel listModel = new DefaultListModel();
private ChatWindowManager chatWindowManager;
/**
* Creates an instance of the <tt>ChatRoomsList</tt>.
*
* @param mainFrame The main application window.
*/
public ChatRoomsList(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
this.chatWindowManager = mainFrame.getChatWindowManager();
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.setModel(listModel);
this.setCellRenderer(new ChatRoomsListCellRenderer());
this.addMouseListener(this);
}
/**
* Adds a chat server and all its existing chat rooms.
*
* @param pps the <tt>ProtocolProviderService</tt> corresponding to the chat
* server
* @param multiUserChatOperationSet the <tt>OperationSetMultiUserChat</tt>
* from which we manage chat rooms
*/
public void addChatServer(ProtocolProviderService pps,
OperationSetMultiUserChat multiUserChatOperationSet)
{
listModel.addElement(pps);
ConfigurationService configService
= GuiActivator.getConfigurationService();
String prefix = "net.java.sip.communicator.impl.gui.accounts";
List accounts = configService
.getPropertyNamesByPrefix(prefix, true);
Iterator accountsIter = accounts.iterator();
while(accountsIter.hasNext()) {
String accountRootPropName
= (String) accountsIter.next();
String accountUID
= configService.getString(accountRootPropName);
if(accountUID.equals(pps
.getAccountID().getAccountUniqueID()))
{
List chatRooms = configService
.getPropertyNamesByPrefix(
accountRootPropName + ".chatRooms", true);
Iterator chatRoomsIter = chatRooms.iterator();
while(chatRoomsIter.hasNext())
{
String chatRoomPropName
= (String) chatRoomsIter.next();
String chatRoomID
= configService.getString(chatRoomPropName);
String chatRoomName = configService.getString(
chatRoomPropName + ".chatRoomName");
ChatRoomWrapper chatRoomWrapper
= new ChatRoomWrapper(pps, chatRoomID, chatRoomName);
this.addChatRoom(chatRoomWrapper);
}
}
}
}
/**
* Adds a chat room to this list.
*
* @param chatRoomWrapper the <tt>ChatRoom</tt> to add
*/
public void addChatRoom(ChatRoomWrapper chatRoomWrapper)
{
int parentIndex = listModel.indexOf(chatRoomWrapper.getParentProvider());
boolean inserted = false;
if(parentIndex != -1)
{
for(int i = parentIndex + 1; i < listModel.getSize(); i ++)
{
Object element = listModel.get(i);
if(element instanceof ProtocolProviderService)
{
listModel.add(i, chatRoomWrapper);
// Indicate that we have found the last chat room in the
// list of server children and we have inserted there the
// new chat room.
inserted = true;
break;
}
}
if(!inserted)
listModel.addElement(chatRoomWrapper);
}
ConfigurationManager.saveChatRoom(
chatRoomWrapper.getParentProvider(),
chatRoomWrapper.getChatRoomID(),
chatRoomWrapper.getChatRoomID(),
chatRoomWrapper.getChatRoomName());
}
/**
* Removes the given <tt>ChatRoom</tt> from the list of all chat rooms.
*
* @param chatRoomWrapper the <tt>ChatRoomWrapper</tt> to remove
*/
public void removeChatRoom(ChatRoomWrapper chatRoomWrapper)
{
listModel.removeElement(chatRoomWrapper);
ConfigurationManager.saveChatRoom(
chatRoomWrapper.getParentProvider(),
chatRoomWrapper.getChatRoomID(),
null, null);
}
/**
* Returns the <tt>ChatRoomWrapper</tt> that correspond to the given
* <tt>ChatRoom</tt>. If the list of chat rooms doesn't contain a
* corresponding wrapper - returns null.
*
* @param chatRoom the <tt>ChatRoom</tt> that we're looking for
* @return the <tt>ChatRoomWrapper</tt> object corresponding to the given
* <tt>ChatRoom</tt>
*/
public ChatRoomWrapper findChatRoomWrapperFromChatRoom(ChatRoom chatRoom)
{
for(int i = 0; i < listModel.getSize(); i ++)
{
Object listItem = listModel.get(i);
if(listItem instanceof ChatRoomWrapper)
{
ChatRoomWrapper chatRoomWrapper = (ChatRoomWrapper) listItem;
if(chatRoom.equals(chatRoomWrapper.getChatRoom()))
{
return chatRoomWrapper;
}
}
}
return null;
}
/**
* Determines if the chat server is closed.
*
* @param pps the protocol provider service that we'll be checking
* @return true if the chat server is closed and false otherwise.
*/
public boolean isChatServerClosed(ProtocolProviderService pps)
{
return false;
}
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
/**
* A chat room was selected. Opens the chat room in the chat window.
*
* @param e the <tt>MouseEvent</tt> instance containing details of
* the event that has just occurred.
*/
public void mousePressed(MouseEvent e)
{
//Select the object under the right button click.
if ((e.getModifiers() & InputEvent.BUTTON2_MASK) != 0
|| (e.getModifiers() & InputEvent.BUTTON3_MASK) != 0
|| (e.isControlDown() && !e.isMetaDown()))
{
this.setSelectedIndex(locationToIndex(e.getPoint()));
}
Object o = this.getSelectedValue();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0)
{
if(o instanceof ChatRoomWrapper)
{
ChatRoomWrapper chatRoomWrapper = (ChatRoomWrapper) o;
ChatWindowManager chatWindowManager
= mainFrame.getChatWindowManager();
- ChatPanel chatPanel
+ ConferenceChatPanel chatPanel
= chatWindowManager.getMultiChat(chatRoomWrapper);
chatWindowManager.openChat(chatPanel, true);
}
}
else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
{
if(o instanceof ProtocolProviderService)
{
ChatRoomServerRightButtonMenu rightButtonMenu
= new ChatRoomServerRightButtonMenu(
mainFrame, (ProtocolProviderService) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
else if (o instanceof ChatRoomWrapper)
{
ChatRoomRightButtonMenu rightButtonMenu
= new ChatRoomRightButtonMenu(mainFrame,
(ChatRoomWrapper) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
}
}
/**
* Goes through the locally stored chat rooms list and for each
* {@link ChatRoomWrapper} tries to find the corresponding server stored
* {@link ChatRoom} in the specified operation set. Joins automatically all
* found chat rooms.
*
* @param protocolProvider the protocol provider for the account to
* synchronize
* @param opSet the multi user chat operation set, which give us access to
* chat room server
*/
public void synchronizeOpSetWithLocalContactList(
ProtocolProviderService protocolProvider,
final OperationSetMultiUserChat opSet)
{
int serverIndex = listModel.indexOf(protocolProvider);
for(int i = serverIndex + 1; i < listModel.size(); i ++)
{
final Object o = listModel.get(i);
if(!(o instanceof ChatRoomWrapper))
break;
new Thread()
{
public void run()
{
ChatRoomWrapper chatRoomWrapper = (ChatRoomWrapper) o;
ChatRoom chatRoom = null;
try
{
chatRoom
= opSet.findRoom(chatRoomWrapper.getChatRoomName());
}
catch (OperationFailedException e1)
{
logger.error("Failed to find chat room with name:"
+ chatRoomWrapper.getChatRoomName(), e1);
}
catch (OperationNotSupportedException e1)
{
logger.error("Failed to find chat room with name:"
+ chatRoomWrapper.getChatRoomName(), e1);
}
if(chatRoom != null)
{
chatRoomWrapper.setChatRoom(chatRoom);
mainFrame.getMultiUserChatManager()
.joinChatRoom(chatRoom);
}
}
}.start();
}
}
/**
* Refreshes the chat room's list. Meant to be invoked when a modification
* in a chat room is made and the list should be refreshed in order to show
* the new state correctly.
*/
public void refresh()
{
this.revalidate();
this.repaint();
}
}
| true | true | public void mousePressed(MouseEvent e)
{
//Select the object under the right button click.
if ((e.getModifiers() & InputEvent.BUTTON2_MASK) != 0
|| (e.getModifiers() & InputEvent.BUTTON3_MASK) != 0
|| (e.isControlDown() && !e.isMetaDown()))
{
this.setSelectedIndex(locationToIndex(e.getPoint()));
}
Object o = this.getSelectedValue();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0)
{
if(o instanceof ChatRoomWrapper)
{
ChatRoomWrapper chatRoomWrapper = (ChatRoomWrapper) o;
ChatWindowManager chatWindowManager
= mainFrame.getChatWindowManager();
ChatPanel chatPanel
= chatWindowManager.getMultiChat(chatRoomWrapper);
chatWindowManager.openChat(chatPanel, true);
}
}
else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
{
if(o instanceof ProtocolProviderService)
{
ChatRoomServerRightButtonMenu rightButtonMenu
= new ChatRoomServerRightButtonMenu(
mainFrame, (ProtocolProviderService) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
else if (o instanceof ChatRoomWrapper)
{
ChatRoomRightButtonMenu rightButtonMenu
= new ChatRoomRightButtonMenu(mainFrame,
(ChatRoomWrapper) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
}
}
| public void mousePressed(MouseEvent e)
{
//Select the object under the right button click.
if ((e.getModifiers() & InputEvent.BUTTON2_MASK) != 0
|| (e.getModifiers() & InputEvent.BUTTON3_MASK) != 0
|| (e.isControlDown() && !e.isMetaDown()))
{
this.setSelectedIndex(locationToIndex(e.getPoint()));
}
Object o = this.getSelectedValue();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0)
{
if(o instanceof ChatRoomWrapper)
{
ChatRoomWrapper chatRoomWrapper = (ChatRoomWrapper) o;
ChatWindowManager chatWindowManager
= mainFrame.getChatWindowManager();
ConferenceChatPanel chatPanel
= chatWindowManager.getMultiChat(chatRoomWrapper);
chatWindowManager.openChat(chatPanel, true);
}
}
else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
{
if(o instanceof ProtocolProviderService)
{
ChatRoomServerRightButtonMenu rightButtonMenu
= new ChatRoomServerRightButtonMenu(
mainFrame, (ProtocolProviderService) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
else if (o instanceof ChatRoomWrapper)
{
ChatRoomRightButtonMenu rightButtonMenu
= new ChatRoomRightButtonMenu(mainFrame,
(ChatRoomWrapper) o);
rightButtonMenu.setInvoker(this);
rightButtonMenu.setLocation(e.getX()
+ mainFrame.getX() + 5, e.getY() + mainFrame.getY()
+ 105);
rightButtonMenu.setVisible(true);
}
}
}
|
diff --git a/server/TruckItServer/app/controllers/BidController.java b/server/TruckItServer/app/controllers/BidController.java
index 88c4430..cf5a0df 100644
--- a/server/TruckItServer/app/controllers/BidController.java
+++ b/server/TruckItServer/app/controllers/BidController.java
@@ -1,61 +1,64 @@
package controllers;
import model.Bid;
import model.Load;
import model.User;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: ericwood
* Date: 8/24/13
* Time: 7:10 AM
* To change this template use File | Settings | File Templates.
*/
public class BidController extends Controller {
public static Result getBids(String userId) {
List<Bid> bids = new ArrayList<Bid>();
Load load = new Load();
load.setLoadDescription("a really big load");
load.setCustomerId("[email protected]");
Bid bid = new Bid();
User biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 1");
+ bid.setBiddingUser(biddingUser);
bid.setPrice(25.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 2");
+ bid.setBiddingUser(biddingUser);
bid.setPrice(15.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 3");
+ bid.setBiddingUser(biddingUser);
bid.setPrice(18.00);
bid.setLoad(load);
bids.add(bid);
return ok(Json.toJson(bids));
}
public static Result createBid() {
Bid newBid = Json.fromJson(request().body().asJson(),Bid.class);
newBid.save();
return ok();
}
}
| false | true | public static Result getBids(String userId) {
List<Bid> bids = new ArrayList<Bid>();
Load load = new Load();
load.setLoadDescription("a really big load");
load.setCustomerId("[email protected]");
Bid bid = new Bid();
User biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 1");
bid.setPrice(25.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 2");
bid.setPrice(15.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 3");
bid.setPrice(18.00);
bid.setLoad(load);
bids.add(bid);
return ok(Json.toJson(bids));
}
| public static Result getBids(String userId) {
List<Bid> bids = new ArrayList<Bid>();
Load load = new Load();
load.setLoadDescription("a really big load");
load.setCustomerId("[email protected]");
Bid bid = new Bid();
User biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 1");
bid.setBiddingUser(biddingUser);
bid.setPrice(25.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 2");
bid.setBiddingUser(biddingUser);
bid.setPrice(15.00);
bid.setLoad(load);
bids.add(bid);
bid = new Bid();
biddingUser = new User();
biddingUser.setUserId("[email protected]");
biddingUser.setHaulerDisplayName("Bidder 3");
bid.setBiddingUser(biddingUser);
bid.setPrice(18.00);
bid.setLoad(load);
bids.add(bid);
return ok(Json.toJson(bids));
}
|
diff --git a/src_unitTests/javax/xml/crypto/test/dsig/ClassLoaderTest.java b/src_unitTests/javax/xml/crypto/test/dsig/ClassLoaderTest.java
index 82b0b9aa..591d8abf 100644
--- a/src_unitTests/javax/xml/crypto/test/dsig/ClassLoaderTest.java
+++ b/src_unitTests/javax/xml/crypto/test/dsig/ClassLoaderTest.java
@@ -1,42 +1,42 @@
package javax.xml.crypto.test.dsig;
import java.lang.reflect.Method;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import junit.framework.*;
/**
* This test uses more than one classloader to load a class (Driver) that
* invokes the XMLSignature API. It tests that there are not provider class
* loading issues with more than one classloader (see 6380953).
*/
public class ClassLoaderTest extends TestCase {
public ClassLoaderTest(String name) {
super(name);
}
public void test_multiple_loaders() throws Exception {
String baseDir = System.getProperty("basedir");
String fs = System.getProperty("file.separator");
File file0 = new File(baseDir + fs + "build" + fs + "classes" + fs);
File file1 = new File(baseDir + fs + "build" + fs + "test" + fs);
URL[] urls = new URL[2];
urls[0] = file0.toURL();
urls[1] = file1.toURL();
URLClassLoader uc1 = new URLClassLoader(urls, null);
URLClassLoader uc2 = new URLClassLoader(urls, null);
Class c1 = uc1.loadClass("javax.xml.crypto.test.dsig.Driver");
Class c2 = uc2.loadClass("javax.xml.crypto.test.dsig.Driver");
Object o1 = c1.newInstance();
Object o2 = c2.newInstance();
- Method m1 = c1.getMethod("dsig", null);
- Method m2 = c2.getMethod("dsig", null);
- m1.invoke(o1, null);
- m2.invoke(o2, null);
+ Method m1 = c1.getMethod("dsig", (Class[]) null);
+ Method m2 = c2.getMethod("dsig", (Class[]) null);
+ m1.invoke(o1, (Object[]) null);
+ m2.invoke(o2, (Object[]) null);
}
}
| true | true | public void test_multiple_loaders() throws Exception {
String baseDir = System.getProperty("basedir");
String fs = System.getProperty("file.separator");
File file0 = new File(baseDir + fs + "build" + fs + "classes" + fs);
File file1 = new File(baseDir + fs + "build" + fs + "test" + fs);
URL[] urls = new URL[2];
urls[0] = file0.toURL();
urls[1] = file1.toURL();
URLClassLoader uc1 = new URLClassLoader(urls, null);
URLClassLoader uc2 = new URLClassLoader(urls, null);
Class c1 = uc1.loadClass("javax.xml.crypto.test.dsig.Driver");
Class c2 = uc2.loadClass("javax.xml.crypto.test.dsig.Driver");
Object o1 = c1.newInstance();
Object o2 = c2.newInstance();
Method m1 = c1.getMethod("dsig", null);
Method m2 = c2.getMethod("dsig", null);
m1.invoke(o1, null);
m2.invoke(o2, null);
}
| public void test_multiple_loaders() throws Exception {
String baseDir = System.getProperty("basedir");
String fs = System.getProperty("file.separator");
File file0 = new File(baseDir + fs + "build" + fs + "classes" + fs);
File file1 = new File(baseDir + fs + "build" + fs + "test" + fs);
URL[] urls = new URL[2];
urls[0] = file0.toURL();
urls[1] = file1.toURL();
URLClassLoader uc1 = new URLClassLoader(urls, null);
URLClassLoader uc2 = new URLClassLoader(urls, null);
Class c1 = uc1.loadClass("javax.xml.crypto.test.dsig.Driver");
Class c2 = uc2.loadClass("javax.xml.crypto.test.dsig.Driver");
Object o1 = c1.newInstance();
Object o2 = c2.newInstance();
Method m1 = c1.getMethod("dsig", (Class[]) null);
Method m2 = c2.getMethod("dsig", (Class[]) null);
m1.invoke(o1, (Object[]) null);
m2.invoke(o2, (Object[]) null);
}
|
diff --git a/src/beatbots/simulation/BeatBotColored.java b/src/beatbots/simulation/BeatBotColored.java
index d157a26..f64809c 100644
--- a/src/beatbots/simulation/BeatBotColored.java
+++ b/src/beatbots/simulation/BeatBotColored.java
@@ -1,50 +1,50 @@
package beatbots.simulation;
import org.newdawn.slick.Animation;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
public strictfp class BeatBotColored extends BeatBot {
private BeatTokenManager beatTokenManager;
private Beat beat;
public BeatBotColored(BeatMachine beatMachine, BulletManager bulletManager, Vector2f startPosition, BeatTokenManager beatTokenManager, Beat beat) {
super(beatMachine, bulletManager, startPosition);
this.beat = beat;
this.beatTokenManager = beatTokenManager;
}
@Override
public strictfp void init(GameContainer gameContainer) throws SlickException {
super.init(gameContainer);
//switch (this.beat) {
//case Red:
- this.animation = new Animation(new Image[] { new Image("assets/BeatBot2Frame1.png"), new Image("assets/BeatBot2Frame2.png") }, 200, true);
+ this.animation = new Animation(new Image[] { new Image("assets/BeatBot2RightFrame1.png"), new Image("assets/BeatBot2RightFrame2.png") }, 200, true);
//break;
//}
this.color = Utils.getBeatColor(this.beat);
}
@Override
protected strictfp void onDestroy() {
super.onDestroy();
this.beatTokenManager.drop(this.getPosition(), this.beat);
}
}
| true | true | public strictfp void init(GameContainer gameContainer) throws SlickException {
super.init(gameContainer);
//switch (this.beat) {
//case Red:
this.animation = new Animation(new Image[] { new Image("assets/BeatBot2Frame1.png"), new Image("assets/BeatBot2Frame2.png") }, 200, true);
//break;
//}
this.color = Utils.getBeatColor(this.beat);
}
| public strictfp void init(GameContainer gameContainer) throws SlickException {
super.init(gameContainer);
//switch (this.beat) {
//case Red:
this.animation = new Animation(new Image[] { new Image("assets/BeatBot2RightFrame1.png"), new Image("assets/BeatBot2RightFrame2.png") }, 200, true);
//break;
//}
this.color = Utils.getBeatColor(this.beat);
}
|
diff --git a/src/biz/bokhorst/xprivacy/XWebView.java b/src/biz/bokhorst/xprivacy/XWebView.java
index f1a94807..63d94206 100644
--- a/src/biz/bokhorst/xprivacy/XWebView.java
+++ b/src/biz/bokhorst/xprivacy/XWebView.java
@@ -1,105 +1,105 @@
package biz.bokhorst.xprivacy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.os.Binder;
import android.util.Log;
import android.webkit.WebView;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
public class XWebView extends XHook {
private Methods mMethod;
private static final List<String> mWebSettings = new ArrayList<String>();
private XWebView(Methods method, String restrictionName) {
super(restrictionName, (method == Methods.constructor ? null : method.name()),
(method == Methods.constructor ? "WebView.constructor" : null));
mMethod = method;
}
public String getClassName() {
return "android.webkit.WebView";
}
// public WebSettings getSettings()
// frameworks/base/core/java/android/webkit/WebView.java
// http://developer.android.com/reference/android/webkit/WebView.html
// public synchronized void setUserAgent(int ua)
// public synchronized void setUserAgentString (String ua)
// frameworks/base/core/java/android/webkit/WebSettings.java
// http://developer.android.com/reference/android/webkit/WebSettings.html
private enum Methods {
constructor, getSettings
};
public static List<XHook> getInstances() {
List<XHook> listHook = new ArrayList<XHook>();
listHook.add(new XWebView(Methods.constructor, PrivacyManager.cView));
listHook.add(new XWebView(Methods.getSettings, PrivacyManager.cView));
return listHook;
}
@Override
protected void before(MethodHookParam param) throws Throwable {
// Do nothing
}
@Override
protected void after(MethodHookParam param) throws Throwable {
if (mMethod == Methods.constructor) {
if (isRestricted(param)) {
String ua = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
WebView webView = (WebView) param.thisObject;
webView.getSettings().setUserAgentString(ua);
}
} else if (mMethod == Methods.getSettings) {
if (param.getResult() != null) {
// Check web settings type
Class<?> clazzWebSettings = param.getResultOrThrowable().getClass();
if (!mWebSettings.contains(clazzWebSettings.getName())) {
mWebSettings.add(clazzWebSettings.getName());
Util.log(this, Log.INFO, "Hooking " + clazzWebSettings.getName());
// setUserAgent
try {
- Method setUserAgent = clazzWebSettings.getDeclaredMethod("setUserAgent", Integer.class);
- Util.log(this, Log.INFO, "Hooking " + setUserAgent.getName());
+ Util.log(this, Log.INFO, "Hooking setUserAgent");
+ Method setUserAgent = clazzWebSettings.getDeclaredMethod("setUserAgent", int.class);
XposedBridge.hookMethod(setUserAgent, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.setResult(null);
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
// setUserAgentString
try {
+ Util.log(this, Log.INFO, "Hooking setUserAgentString");
Method setUserAgentString = clazzWebSettings.getDeclaredMethod("setUserAgentString",
String.class);
- Util.log(this, Log.INFO, "Hooking " + setUserAgentString.getName());
XposedBridge.hookMethod(setUserAgentString, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.args[0] = PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
}
}
} else
Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
}
}
| false | true | protected void after(MethodHookParam param) throws Throwable {
if (mMethod == Methods.constructor) {
if (isRestricted(param)) {
String ua = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
WebView webView = (WebView) param.thisObject;
webView.getSettings().setUserAgentString(ua);
}
} else if (mMethod == Methods.getSettings) {
if (param.getResult() != null) {
// Check web settings type
Class<?> clazzWebSettings = param.getResultOrThrowable().getClass();
if (!mWebSettings.contains(clazzWebSettings.getName())) {
mWebSettings.add(clazzWebSettings.getName());
Util.log(this, Log.INFO, "Hooking " + clazzWebSettings.getName());
// setUserAgent
try {
Method setUserAgent = clazzWebSettings.getDeclaredMethod("setUserAgent", Integer.class);
Util.log(this, Log.INFO, "Hooking " + setUserAgent.getName());
XposedBridge.hookMethod(setUserAgent, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.setResult(null);
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
// setUserAgentString
try {
Method setUserAgentString = clazzWebSettings.getDeclaredMethod("setUserAgentString",
String.class);
Util.log(this, Log.INFO, "Hooking " + setUserAgentString.getName());
XposedBridge.hookMethod(setUserAgentString, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.args[0] = PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
}
}
} else
Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
}
| protected void after(MethodHookParam param) throws Throwable {
if (mMethod == Methods.constructor) {
if (isRestricted(param)) {
String ua = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
WebView webView = (WebView) param.thisObject;
webView.getSettings().setUserAgentString(ua);
}
} else if (mMethod == Methods.getSettings) {
if (param.getResult() != null) {
// Check web settings type
Class<?> clazzWebSettings = param.getResultOrThrowable().getClass();
if (!mWebSettings.contains(clazzWebSettings.getName())) {
mWebSettings.add(clazzWebSettings.getName());
Util.log(this, Log.INFO, "Hooking " + clazzWebSettings.getName());
// setUserAgent
try {
Util.log(this, Log.INFO, "Hooking setUserAgent");
Method setUserAgent = clazzWebSettings.getDeclaredMethod("setUserAgent", int.class);
XposedBridge.hookMethod(setUserAgent, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.setResult(null);
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
// setUserAgentString
try {
Util.log(this, Log.INFO, "Hooking setUserAgentString");
Method setUserAgentString = clazzWebSettings.getDeclaredMethod("setUserAgentString",
String.class);
XposedBridge.hookMethod(setUserAgentString, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (isRestricted(param))
param.args[0] = PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA");
}
});
} catch (NoSuchFieldError ex) {
Util.bug(this, ex);
}
}
}
} else
Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
}
|
diff --git a/src/test/java/de/ui/sushi/fs/CopyDiffTest.java b/src/test/java/de/ui/sushi/fs/CopyDiffTest.java
index 210f93fc..bcc6eb0e 100644
--- a/src/test/java/de/ui/sushi/fs/CopyDiffTest.java
+++ b/src/test/java/de/ui/sushi/fs/CopyDiffTest.java
@@ -1,212 +1,222 @@
/*
* Copyright 1&1 Internet AG, http://www.1and1.org
*
* 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.ui.sushi.fs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import de.ui.sushi.util.Substitution;
public class CopyDiffTest {
private IO io;
private Map<String, String> variables;
private Copy copy;
public CopyDiffTest() throws IOException {
io = new IO();
variables = new HashMap<String, String>();
copy = new Copy(io.getTemp().createTempDirectory(),
io.filter().includeAll(), true,
variables, Substitution.path(), Substitution.ant(), Copy.DEFAULT_CONTEXT_DELIMITER, Copy.DEFAULT_CALL_PREFIX);
}
@Test
public void mode() throws Exception {
Node destdir;
Node file;
destdir = copy.getSourceDir().getIO().getTemp().createTempDirectory();
file = copy.getSourceDir().join("file");
file.writeString("foo");
file.setMode(0700);
copy.directory(destdir);
assertEquals(0700, destdir.join("file").getMode());
file.setMode(0655);
assertEquals("m file\n", brief(destdir));
copy.directory(destdir);
assertEquals(0655, destdir.join("file").getMode());
}
@Test
public void diff() throws Exception {
Node left;
Node right;
left = io.getTemp().createTempDirectory();
right = io.getTemp().createTempDirectory();
left.join("left").writeString("1");
right.join("right").writeString("2");
assertEquals("R left\nA right\n", left.diffDirectory(right, true));
assertEquals("A right\n", new Diff(true).directory(left, right, "right"));
}
@Test
public void template() throws Exception {
Node destdir;
String brief;
+ String normal;
destdir = copy.getSourceDir().getIO().getTemp().createTempDirectory();
variables.put("home", "mhm");
variables.put("machine", "walter");
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
copy.getSourceDir().join("file").writeLines("home: ${home}", "machine: ${machine}");
assertEquals("A file\n", brief(destdir));
assertEquals("### file\n" +
"+ home: mhm\n" +
"+ machine: walter\n", diff(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder").mkdir();
assertEquals("A folder\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("superdir/subdir").mkdirs();
assertEquals("A superdir\nA superdir/subdir\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder/file").writeLines("home: ${home}\n", "machine: ${machine}\n");
assertEquals("A folder/file\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
variables.put("machine", "fritz");
brief = brief(destdir);
assertTrue(brief, brief.equals("M folder/file\nM file\n") || brief.equals("M file\nM folder/file\n"));
- assertEquals("### folder/file\n" +
+ normal = diff(destdir);
+ assertTrue(normal,
+ ("### folder/file\n" +
"-machine: walter\n" +
"+machine: fritz\n" +
"### file\n" +
"-machine: walter\n" +
- "+machine: fritz\n", diff(destdir));
+ "+machine: fritz\n").equals(normal) ||
+ ("### file\n" +
+ "-machine: walter\n" +
+ "+machine: fritz\n" +
+ "### folder/file\n" +
+ "-machine: walter\n" +
+ "+machine: fritz\n").equals(normal)
+ );
copy.directory(destdir);
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
}
@Test
public void templateExt() throws Exception {
CopyExt foo;
IO io;
Node src;
Node dest;
Map<String, String> context;
io = new IO();
src = io.guessProjectHome(getClass()).join("src/test/template");
dest = io.getTemp().createTempDirectory().join("dest").mkdir();
context = new HashMap<String, String>();
context.put("var", "value");
context.put("name", "foo");
foo = new CopyExt(src, context);
foo.directory(dest);
assertEquals("testdir", foo.called);
assertEquals("value", dest.join("testfile").readString());
assertEquals("", dest.join("a").readString());
assertEquals("value\n", dest.join("b").readString());
assertEquals("bar", dest.join("foo").readString());
assertEquals("bar", dest.join("foo").readString());
assertEquals("1", dest.join("file1").readString());
assertEquals("2", dest.join("file2").readString());
assertEquals("11", dest.join("file11").readString());
assertEquals("12", dest.join("file12").readString());
assertEquals("21", dest.join("file21").readString());
assertEquals("22", dest.join("file22").readString());
assertEquals("1", dest.join("dir1/file").readString());
assertEquals("2", dest.join("dir2/file").readString());
}
private String diff(Node destdir) throws IOException {
return doDiff(destdir, false);
}
private String brief(Node destdir) throws IOException {
return doDiff(destdir, true);
}
private String doDiff(Node destdir, boolean brief) throws IOException {
Node tmp = io.getTemp().createTempDirectory();
copy.directory(tmp);
return destdir.diffDirectory(tmp, brief);
}
public static class CopyExt extends Copy {
public String called = null;
public CopyExt(Node srcdir, Map<String, String> variables) {
super(srcdir, srcdir.getIO().filter().includeAll(), false, variables, Copy.DEFAULT_SUBST, Copy.DEFAULT_SUBST, '-', '@');
}
public List<Map<String, String>> contextN(Map<String, String> parent) {
return ctx(parent, "n");
}
public List<Map<String, String>> contextMoreNumbers(Map<String, String> parent) {
return ctx(parent, "m");
}
public void callTestDir(Node node, Map<String, String> context) {
called = node.getName();
}
public String callTestFile(Map<String, String> context) {
return context.get("var");
}
private List<Map<String, String>> ctx(Map<String, String> parent, String name) {
List<Map<String, String>> result;
result = new ArrayList<Map<String, String>>();
result.add(map(parent, name, 1));
result.add(map(parent, name, 2));
return result;
}
private static Map<String, String> map(Map<String, String> parent, String name, int n) {
Map<String, String> result;
result = new HashMap<String, String>(parent);
result.put(name, Integer.toString(n));
return result;
}
}
}
| false | true | public void template() throws Exception {
Node destdir;
String brief;
destdir = copy.getSourceDir().getIO().getTemp().createTempDirectory();
variables.put("home", "mhm");
variables.put("machine", "walter");
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
copy.getSourceDir().join("file").writeLines("home: ${home}", "machine: ${machine}");
assertEquals("A file\n", brief(destdir));
assertEquals("### file\n" +
"+ home: mhm\n" +
"+ machine: walter\n", diff(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder").mkdir();
assertEquals("A folder\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("superdir/subdir").mkdirs();
assertEquals("A superdir\nA superdir/subdir\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder/file").writeLines("home: ${home}\n", "machine: ${machine}\n");
assertEquals("A folder/file\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
variables.put("machine", "fritz");
brief = brief(destdir);
assertTrue(brief, brief.equals("M folder/file\nM file\n") || brief.equals("M file\nM folder/file\n"));
assertEquals("### folder/file\n" +
"-machine: walter\n" +
"+machine: fritz\n" +
"### file\n" +
"-machine: walter\n" +
"+machine: fritz\n", diff(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
}
| public void template() throws Exception {
Node destdir;
String brief;
String normal;
destdir = copy.getSourceDir().getIO().getTemp().createTempDirectory();
variables.put("home", "mhm");
variables.put("machine", "walter");
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
copy.getSourceDir().join("file").writeLines("home: ${home}", "machine: ${machine}");
assertEquals("A file\n", brief(destdir));
assertEquals("### file\n" +
"+ home: mhm\n" +
"+ machine: walter\n", diff(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder").mkdir();
assertEquals("A folder\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("superdir/subdir").mkdirs();
assertEquals("A superdir\nA superdir/subdir\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
copy.getSourceDir().join("folder/file").writeLines("home: ${home}\n", "machine: ${machine}\n");
assertEquals("A folder/file\n", brief(destdir));
copy.directory(destdir);
assertEquals("", brief(destdir));
variables.put("machine", "fritz");
brief = brief(destdir);
assertTrue(brief, brief.equals("M folder/file\nM file\n") || brief.equals("M file\nM folder/file\n"));
normal = diff(destdir);
assertTrue(normal,
("### folder/file\n" +
"-machine: walter\n" +
"+machine: fritz\n" +
"### file\n" +
"-machine: walter\n" +
"+machine: fritz\n").equals(normal) ||
("### file\n" +
"-machine: walter\n" +
"+machine: fritz\n" +
"### folder/file\n" +
"-machine: walter\n" +
"+machine: fritz\n").equals(normal)
);
copy.directory(destdir);
assertEquals("", brief(destdir));
assertEquals("", diff(destdir));
}
|
diff --git a/src/org/gots/utils/GotsProgressBar.java b/src/org/gots/utils/GotsProgressBar.java
index f3df2c92..ad4be68c 100644
--- a/src/org/gots/utils/GotsProgressBar.java
+++ b/src/org/gots/utils/GotsProgressBar.java
@@ -1,112 +1,112 @@
/*******************************************************************************
* Copyright (c) 2012 sfleury.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* sfleury - initial API and implementation
******************************************************************************/
package org.gots.utils;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class GotsProgressBar extends View {
private int mMax = 1;
private int mProgress = 1;
final public static int HORIZONTAL_STYLE = 1;
final public static int VERTICAL_STYLE = 2;
private int orientation = HORIZONTAL_STYLE;
public GotsProgressBar(Context context) {
super(context);
setMeasuredDimension(10, getMeasuredHeight());
}
public GotsProgressBar(Context context, int orientation) {
super(context);
setMeasuredDimension(10, getMeasuredHeight());
this.orientation = orientation;
}
public GotsProgressBar(Context context, AttributeSet as) {
super(context, as);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (orientation == VERTICAL_STYLE)
setMeasuredDimension(10, MeasureSpec.getSize(heightMeasureSpec));
else
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), 10);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
canvas.drawLine(0, 0, 0, getHeight() - 1, paint);
canvas.drawLine(getWidth() - 1, 0, getWidth() - 1, getHeight() - 1, paint);
canvas.drawLine(0, 0, getWidth() - 1, 0, paint);
canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, paint);
paint.setColor(Color.argb(200, 255, 255, 255));
RectF rectbg;
rectbg = new RectF(1, 1, getWidth() - 1, getHeight() - 1);
// else
// rectbg = new RectF(1, getHeight() - 1, 1, getWidth() - 1);
canvas.drawRect(rectbg, paint);
Float percent = new Float(mProgress) / new Float(mMax) * 100f;
Log.i("percent", "" + percent);
if (percent > 100f)
percent = 100f;
if (percent >= 99f)
paint.setColor(Color.RED);
else if (percent >= 90f)
paint.setColor(Color.rgb(255, 140, 0));
else
paint.setARGB(255, 80, 150, 30);
// int height=new Float(f*getHeight()).intValue();
RectF rect2;
if (orientation == VERTICAL_STYLE){
int f = (getHeight() - 1) * percent.intValue() / 100;
rect2 = new RectF(1, getHeight() - 1, getWidth() - 1, getHeight() - f);}
else{
int f = (getWidth() - 1) * percent.intValue() / 100;
- rect2 = new RectF(1, 1, getWidth() - f, getHeight() - 1);
+ rect2 = new RectF(1, 1, f, getHeight() - 1);
}
canvas.drawRect(rect2, paint);
super.onDraw(canvas);
canvas.restore();
}
public void setMax(int max) {
this.mMax = max;
}
public void setProgress(int progress) {
this.mProgress = progress;
}
}
| true | true | protected void onDraw(Canvas canvas) {
canvas.save();
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
canvas.drawLine(0, 0, 0, getHeight() - 1, paint);
canvas.drawLine(getWidth() - 1, 0, getWidth() - 1, getHeight() - 1, paint);
canvas.drawLine(0, 0, getWidth() - 1, 0, paint);
canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, paint);
paint.setColor(Color.argb(200, 255, 255, 255));
RectF rectbg;
rectbg = new RectF(1, 1, getWidth() - 1, getHeight() - 1);
// else
// rectbg = new RectF(1, getHeight() - 1, 1, getWidth() - 1);
canvas.drawRect(rectbg, paint);
Float percent = new Float(mProgress) / new Float(mMax) * 100f;
Log.i("percent", "" + percent);
if (percent > 100f)
percent = 100f;
if (percent >= 99f)
paint.setColor(Color.RED);
else if (percent >= 90f)
paint.setColor(Color.rgb(255, 140, 0));
else
paint.setARGB(255, 80, 150, 30);
// int height=new Float(f*getHeight()).intValue();
RectF rect2;
if (orientation == VERTICAL_STYLE){
int f = (getHeight() - 1) * percent.intValue() / 100;
rect2 = new RectF(1, getHeight() - 1, getWidth() - 1, getHeight() - f);}
else{
int f = (getWidth() - 1) * percent.intValue() / 100;
rect2 = new RectF(1, 1, getWidth() - f, getHeight() - 1);
}
canvas.drawRect(rect2, paint);
super.onDraw(canvas);
canvas.restore();
}
| protected void onDraw(Canvas canvas) {
canvas.save();
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
canvas.drawLine(0, 0, 0, getHeight() - 1, paint);
canvas.drawLine(getWidth() - 1, 0, getWidth() - 1, getHeight() - 1, paint);
canvas.drawLine(0, 0, getWidth() - 1, 0, paint);
canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, paint);
paint.setColor(Color.argb(200, 255, 255, 255));
RectF rectbg;
rectbg = new RectF(1, 1, getWidth() - 1, getHeight() - 1);
// else
// rectbg = new RectF(1, getHeight() - 1, 1, getWidth() - 1);
canvas.drawRect(rectbg, paint);
Float percent = new Float(mProgress) / new Float(mMax) * 100f;
Log.i("percent", "" + percent);
if (percent > 100f)
percent = 100f;
if (percent >= 99f)
paint.setColor(Color.RED);
else if (percent >= 90f)
paint.setColor(Color.rgb(255, 140, 0));
else
paint.setARGB(255, 80, 150, 30);
// int height=new Float(f*getHeight()).intValue();
RectF rect2;
if (orientation == VERTICAL_STYLE){
int f = (getHeight() - 1) * percent.intValue() / 100;
rect2 = new RectF(1, getHeight() - 1, getWidth() - 1, getHeight() - f);}
else{
int f = (getWidth() - 1) * percent.intValue() / 100;
rect2 = new RectF(1, 1, f, getHeight() - 1);
}
canvas.drawRect(rect2, paint);
super.onDraw(canvas);
canvas.restore();
}
|
diff --git a/source/RMG/jing/rxn/Reaction.java b/source/RMG/jing/rxn/Reaction.java
index 128ea0d8..83eef8db 100644
--- a/source/RMG/jing/rxn/Reaction.java
+++ b/source/RMG/jing/rxn/Reaction.java
@@ -1,1511 +1,1514 @@
// //////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// //////////////////////////////////////////////////////////////////////////////
package jing.rxn;
import java.io.*;
import jing.chem.*;
import java.util.*;
import jing.param.*;
import jing.mathTool.*;
import jing.chemParser.*;
import jing.chem.Species;
import jing.param.Temperature;
import jing.rxnSys.Logger;
import jing.rxnSys.NegativeConcentrationException;
import jing.rxnSys.ReactionModelGenerator;
import jing.rxnSys.SystemSnapshot;
// ## package jing::rxn
// ----------------------------------------------------------------------------
// jing\rxn\Reaction.java
// ----------------------------------------------------------------------------
/**
* Immutable objects.
*/
// ## class Reaction
public class Reaction {
protected static double TRIMOLECULAR_RATE_UPPER = 1.0E100;
protected static double BIMOLECULAR_RATE_UPPER = 1.0E100; // ## attribute BIMOLECULAR_RATE_UPPER
protected static double UNIMOLECULAR_RATE_UPPER = 1.0E100; // ## attribute UNIMOLECULAR_RATE_UPPER
protected String comments = "No comment"; // ## attribute comments
protected Kinetics[] fittedReverseKinetics = null; // ## attribute fittedReverseKinetics
protected double rateConstant;
protected Reaction reverseReaction = null; // ## attribute reverseReaction
protected Kinetics[] kinetics;
protected Structure structure;
protected double UpperBoundRate;// svp
protected double LowerBoundRate;// svp
protected boolean finalized = false;
protected String ChemkinString = null;
protected boolean kineticsFromPrimaryKineticLibrary = false;
protected boolean expectDuplicate = false;
// Constructors
// ## operation Reaction()
public Reaction() {
// #[ operation Reaction()
// #]
}
// ## operation Reaction(Structure,RateConstant)
private Reaction(Structure p_structure, Kinetics[] p_kinetics) {
// #[ operation Reaction(Structure,RateConstant)
structure = p_structure;
kinetics = p_kinetics;
// rateConstant = calculateTotalRate(Global.temperature);
// #]
}
// ## operation allProductsIncluded(LinkedHashSet)
public boolean allProductsIncluded(LinkedHashSet p_speciesSet) {
// #[ operation allProductsIncluded(LinkedHashSet)
Iterator iter = getProducts();
while (iter.hasNext()) {
Species spe = ((Species) iter.next());
if (!p_speciesSet.contains(spe))
return false;
}
return true;
// #]
}
// ## operation allReactantsIncluded(LinkedHashSet)
public boolean allReactantsIncluded(LinkedHashSet p_speciesSet) {
// #[ operation allReactantsIncluded(LinkedHashSet)
if (p_speciesSet == null)
throw new NullPointerException();
Iterator iter = getReactants();
while (iter.hasNext()) {
Species spe = ((Species) iter.next());
if (!p_speciesSet.contains(spe))
return false;
}
return true;
// #]
}
/**
* Calculate this reaction's thermo parameter. Basically, make addition of the thermo parameters of all the
* reactants and products.
*/
// ## operation calculateHrxn(Temperature)
public double calculateHrxn(Temperature p_temperature) {
// #[ operation calculateHrxn(Temperature)
return structure.calculateHrxn(p_temperature);
// #]
}
// ## operation calculateKeq(Temperature)
public double calculateKeq(Temperature p_temperature) {
// #[ operation calculateKeq(Temperature)
return structure.calculateKeq(p_temperature);
// #]
}
// ## operation calculateKeqUpperBound(Temperature)
// svp
public double calculateKeqUpperBound(Temperature p_temperature) {
// #[ operation calculateKeqUpperBound(Temperature)
return structure.calculateKeqUpperBound(p_temperature);
// #]
}
// ## operation calculateKeqLowerBound(Temperature)
// svp
public double calculateKeqLowerBound(Temperature p_temperature) {
// #[ operation calculateKeqLowerBound(Temperature)
return structure.calculateKeqLowerBound(p_temperature);
// #]
}
public double calculateTotalRate(Temperature p_temperature) {
double rate = 0;
Temperature stdtemp = new Temperature(298, "K");
double Hrxn = calculateHrxn(stdtemp);
Temperature sys_temp = ReactionModelGenerator.getTemp4BestKinetics();
/*
* AJ 12JULY2010: Added diffusive limits from previous RMG version by replacing function calculateTotalRate
* Checks the exothermicity and molecularity of reaction to determine the diffusive rate limit
*/
/*
* 29Jun2009-MRH: Added a kinetics from PRL check If the kinetics for this reaction is from a PRL, use those
* numbers to compute the rate. Else, proceed as before.
*/
/*
* MRH 18MAR2010: Changing the structure of a reaction's kinetics If the kinetics are from a primary kinetic
* library, we assume the user has supplied the total pre-exponential factor for the reaction (and not the
* per-event pre-exponential facor). If the kinetics were estimated by RMG, the pre-exponential factor must be
* multiplied by the "redundancy" (# of events)
*/
if (kineticsFromPrimaryKineticLibrary) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
rate += k.calculateRate(p_temperature, Hrxn);
+ }
+ if(isBackward()){
+ rate = rate * calculateKeq(p_temperature);
}
return rate;
} else if (isForward()) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
if ((int) structure.redundancy != 1) {
k = k.multiply(structure.redundancy);
}
rate += k.calculateRate(p_temperature, Hrxn);
}
/*
* Diffusion limits added by AJ on July 12, 2010 Requires correction in the forward direction only, reverse
* reaction corrects itself If ReactionModelGenerator.useDiffusion is true (solvation is on) compute kd and
* return keff
*/
if (ReactionModelGenerator.getUseDiffusion()) {
int numReacts = structure.getReactantNumber();
int numProds = structure.getProductNumber();
double keff = 0.0;
double DiffFactor = 0.0;
if (numReacts == 1 && numProds == 1) {
keff = rate;
rate = keff;
DiffFactor = 1;
} else if (numReacts == 1 && numProds == 2) {
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 1) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 2) {
double rxn_Keq = structure.calculateKeq(p_temperature);
double deltaHrxn = structure.calculateHrxn(p_temperature);
if (rxn_Keq > 1) { // Forward reaction is exothermic hence the corresponding diffusion limit applies
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (rxn_Keq < 1) { // Reverse reaction is exothermic and the corresponding diffusion limit
// should be used
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
}
} else if (numReacts == 2 && numProds == 3) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 4) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
}
// Add comments only if the temperature at which the function has been called corresponds to the system
// temperature specified in the condition file
// And if they haven't already been added
if (p_temperature.getK() == sys_temp.getK()) {
String oldComments = k_All[0].getComment();
if (!oldComments.contains("Diffusion")) {
if (numReacts == 1 && numProds == 1)
oldComments += " Unimolecular: no diffusion limitation.";
String newComments = oldComments
+ String.format(
" Diffusion factor=%.3g, rate=%.3g, Keq=%.3g, at T=%.0fK.",
DiffFactor, rate,
calculateKeq(p_temperature),
p_temperature.getK());
setKineticsComments(newComments, 0);
}
}
}
return rate;
} else if (isBackward()) {
Reaction r = getReverseReaction();
rate = r.calculateTotalRate(p_temperature);
return rate * calculateKeq(p_temperature);
} else {
throw new InvalidReactionDirectionException();
}
}
// ## operation calculatediff(LinkedList)
public double calculatediff(LinkedList p_struct) {
if (p_struct.size() != 2) {
Logger.warning("Cannot compute diffusive limit if number of reactants is not equal to 2");
}
// Array containing the radii of the two species passed in p_struct
double[] r;
double[] d;
r = new double[2];
d = new double[2];
int i = 0;
for (Iterator iter = p_struct.iterator(); iter.hasNext();) {
Species sp = (Species) iter.next();
ChemGraph cg = sp.getChemGraph();
r[i] = cg.getRadius();
d[i] = cg.getDiffusivity();
i = i + 1;
}
double kdiff;
kdiff = (88 / 7) * (d[0] + d[1]) * (r[0] + r[1]) * 6.023e29; // units of r[i]=m; d[1]=m2/sec; kdiff=cm3/mole sec
return kdiff;
}
// ## operation calculateUpperBoundRate(Temperature)
// svp
public double calculateUpperBoundRate(Temperature p_temperature) {
// #[ operation calculateUpperBoundRate(Temperature)
if (isForward()) {
double A;
double E;
double n;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
A = kinetics[numKinetics].getA().getUpperBound();
E = kinetics[numKinetics].getE().getLowerBound();
n = kinetics[numKinetics].getN().getUpperBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue() * 1.2;
}
// Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics) {
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics) kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
} else {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
}
}
if (E < 0) {
E = 0;
}
double indiv_k = 0.0;
indiv_k = A
* Math.pow(p_temperature.getK(), n)
* Math.exp(-E / GasConstant.getKcalMolK()
/ p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
UpperBoundRate += indiv_k;
}
return UpperBoundRate;
} else if (isBackward()) {
Reaction r = getReverseReaction();
if (r == null)
throw new NullPointerException("Reverse reaction is null.\n"
+ structure.toString());
if (!r.isForward())
throw new InvalidReactionDirectionException();
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
double A = kinetics[numKinetics].getA().getUpperBound();
double E = kinetics[numKinetics].getE().getLowerBound();
double n = kinetics[numKinetics].getN().getUpperBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue() * 1.2;
}
// Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics) {
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics) kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
} else {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
}
}
if (E < 0) {
E = 0;
}
double indiv_k = 0.0;
indiv_k = A
* Math.pow(p_temperature.getK(), n)
* Math.exp(-E / GasConstant.getKcalMolK()
/ p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
UpperBoundRate += indiv_k
* calculateKeqUpperBound(p_temperature);
}
return UpperBoundRate;
} else {
throw new InvalidReactionDirectionException();
}
// #]
}
// ## operation calculateLowerBoundRate(Temperature)
// svp
public double calculateLowerBoundRate(Temperature p_temperature) {
// #[ operation calculateLowerBoundRate(Temperature)
if (isForward()) {
for (int numKinetics = 0; numKinetics < kinetics.length; ++numKinetics) {
double A = kinetics[numKinetics].getA().getLowerBound();
double E = kinetics[numKinetics].getE().getUpperBound();
double n = kinetics[numKinetics].getN().getLowerBound();
if (A > 1E300 || A <= 0) {
A = kinetics[numKinetics].getA().getValue() / 1.2;
}
// Kinetics kinetics = getRateConstant().getKinetics();
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics) {
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics) kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
} else {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
}
}
double indiv_k = 0.0;
indiv_k = A
* Math.pow(p_temperature.getK(), n)
* Math.exp(-E / GasConstant.getKcalMolK()
/ p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
LowerBoundRate += indiv_k;
}
return LowerBoundRate;
} else if (isBackward()) {
Reaction r = getReverseReaction();
if (r == null)
throw new NullPointerException("Reverse reaction is null.\n"
+ structure.toString());
if (!r.isForward())
throw new InvalidReactionDirectionException();
for (int numKinetics = 0; numKinetics < kinetics.length; ++numKinetics) {
double A = kinetics[numKinetics].getA().getLowerBound();
double E = kinetics[numKinetics].getE().getUpperBound();
double n = kinetics[numKinetics].getN().getLowerBound();
if (A > 1E300) {
A = kinetics[numKinetics].getA().getValue() / 1.2;
}
if (kinetics[numKinetics] instanceof ArrheniusEPKinetics) {
ArrheniusEPKinetics arrhenius = (ArrheniusEPKinetics) kinetics[numKinetics];
double H = calculateHrxn(p_temperature);
if (H < 0) {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
}
} else {
if (arrhenius.getAlpha().getValue() > 0) {
double alpha = arrhenius.getAlpha().getUpperBound();
E = E + alpha * H;
} else {
double alpha = arrhenius.getAlpha().getLowerBound();
E = E + alpha * H;
}
}
}
double indiv_k = 0.0;
indiv_k = A
* Math.pow(p_temperature.getK(), n)
* Math.exp(-E / GasConstant.getKcalMolK()
/ p_temperature.getK());
indiv_k *= getStructure().getRedundancy();
LowerBoundRate += indiv_k
* calculateKeqLowerBound(p_temperature);
}
return LowerBoundRate;
} else {
throw new InvalidReactionDirectionException();
}
// #]
}
// ## operation calculateSrxn(Temperature)
public double calculateSrxn(Temperature p_temperature) {
// #[ operation calculateSrxn(Temperature)
return structure.calculateSrxn(p_temperature);
// #]
}
// ## operation calculateThirdBodyCoefficient(SystemSnapshot)
public double calculateThirdBodyCoefficient(SystemSnapshot p_presentStatus) {
// #[ operation calculateThirdBodyCoefficient(SystemSnapshot)
if (!(this instanceof ThirdBodyReaction))
return 1;
else {
return ((ThirdBodyReaction) this)
.calculateThirdBodyCoefficient(p_presentStatus);
}
// #]
}
// ## operation checkRateRange()
public boolean checkRateRange() {
// #[ operation checkRateRange()
Temperature t = new Temperature(1500, "K");
double rate = calculateTotalRate(t);
if (getReactantNumber() == 2) {
if (rate > BIMOLECULAR_RATE_UPPER)
return false;
} else if (getReactantNumber() == 1) {
if (rate > UNIMOLECULAR_RATE_UPPER)
return false;
} else if (getReactantNumber() == 3) {
if (rate > TRIMOLECULAR_RATE_UPPER)
return false;
} else
throw new InvalidReactantNumberException();
return true;
// #]
}
// ## operation contains(Species)
public boolean contains(Species p_species) {
// #[ operation contains(Species)
if (containsAsReactant(p_species) || containsAsProduct(p_species))
return true;
else
return false;
// #]
}
// ## operation containsAsProduct(Species)
public boolean containsAsProduct(Species p_species) {
// #[ operation containsAsProduct(Species)
Iterator iter = getProducts();
while (iter.hasNext()) {
// ChemGraph cg = (ChemGraph)iter.next();
Species spe = (Species) iter.next();
if (spe.equals(p_species))
return true;
}
return false;
// #]
}
// ## operation containsAsReactant(Species)
public boolean containsAsReactant(Species p_species) {
// #[ operation containsAsReactant(Species)
Iterator iter = getReactants();
while (iter.hasNext()) {
// ChemGraph cg = (ChemGraph)iter.next();
Species spe = (Species) iter.next();
if (spe.equals(p_species))
return true;
}
return false;
// #]
}
/**
* Checks if the structure of the reaction is the same. Does not check the rate constant. Two reactions with the
* same structure but different rate constants will be equal.
*/
// ## operation equals(Object)
public boolean equals(Object p_reaction) {
// #[ operation equals(Object)
if (this == p_reaction)
return true;
if (!(p_reaction instanceof Reaction))
return false;
Reaction r = (Reaction) p_reaction;
if (!getStructure().equals(r.getStructure()))
return false;
return true;
}
/*
* // fitReverseKineticsPrecisely and getPreciseReverseKinetics // are not used, not maintained, and we have clue what
* they do, // so we're commenting them out so we don't keep looking at them. // (oh, and they look pretty similar to
* each other!) // - RWest & JWAllen, June 2009 //## operation fitReverseKineticsPrecisely() public void
* fitReverseKineticsPrecisely() { //#[ operation fitReverseKineticsPrecisely() if (isForward()) { fittedReverseKinetics
* = null; } else { String result = ""; for (double t = 300.0; t<1500.0; t+=50.0) { double rate = calculateTotalRate(new
* Temperature(t,"K")); result += String.valueOf(t) + '\t' + String.valueOf(rate) + '\n'; } // run fit3p String dir =
* System.getProperty("RMG.workingDirectory"); File fit3p_input; try { // prepare fit3p input file, "input.dat" is the
* input file name fit3p_input = new File("fit3p/input.dat"); FileWriter fw = new FileWriter(fit3p_input);
* fw.write(result); fw.close(); } catch (IOException e) { System.out.println("Wrong input file for fit3p!");
* System.out.println(e.getMessage()); System.exit(0); } try { // system call for fit3p String[] command = {dir+
* "/bin/fit3pbnd.exe"}; File runningDir = new File("fit3p"); Process fit = Runtime.getRuntime().exec(command, null,
* runningDir); int exitValue = fit.waitFor(); } catch (Exception e) { System.out.println("Error in run fit3p!");
* System.out.println(e.getMessage()); System.exit(0); } // parse the output file from chemdis try { String fit3p_output
* = "fit3p/output.dat"; FileReader in = new FileReader(fit3p_output); BufferedReader data = new BufferedReader(in);
* String line = ChemParser.readMeaningfulLine(data); line = line.trim(); StringTokenizer st = new
* StringTokenizer(line); String A = st.nextToken(); String temp = st.nextToken(); temp = st.nextToken(); temp =
* st.nextToken(); double Ar = Double.parseDouble(temp); line = ChemParser.readMeaningfulLine(data); line = line.trim();
* st = new StringTokenizer(line); String n = st.nextToken(); temp = st.nextToken(); temp = st.nextToken(); double nr =
* Double.parseDouble(temp); line = ChemParser.readMeaningfulLine(data); line = line.trim(); st = new
* StringTokenizer(line); String E = st.nextToken(); temp = st.nextToken(); temp = st.nextToken(); temp =
* st.nextToken(); double Er = Double.parseDouble(temp); if (Er < 0) { System.err.println(getStructure().toString());
* System.err.println("fitted Er < 0: "+Double.toString(Er)); double increase =
* Math.exp(-Er/GasConstant.getKcalMolK()/715.0); double deltan = Math.log(increase)/Math.log(715.0);
* System.err.println("n enlarged by factor of: " + Double.toString(deltan)); nr += deltan; Er = 0; } UncertainDouble
* udAr = new UncertainDouble(Ar, 0, "Adder"); UncertainDouble udnr = new UncertainDouble(nr, 0, "Adder");
* UncertainDouble udEr = new UncertainDouble(Er, 0, "Adder"); fittedReverseKinetics = new ArrheniusKinetics(udAr, udnr
* , udEr, "300-1500", 1, "fitting from forward and thermal",null); in.close(); } catch (Exception e) {
* System.out.println("Error in read output.dat from fit3p!"); System.out.println(e.getMessage()); System.exit(0); } }
* return; //#] } //## operation fitReverseKineticsPrecisely() public Kinetics getPreciseReverseKinetics() { //#[
* operation fitReverseKineticsPrecisely() Kinetics fittedReverseKinetics =null; String result = ""; for (double t =
* 300.0; t<1500.0; t+=50.0) { double rate = calculateTotalRate(new Temperature(t,"K")); result += String.valueOf(t) +
* '\t' + String.valueOf(rate) + '\n'; } // run fit3p String dir = System.getProperty("RMG.workingDirectory"); File
* fit3p_input; try { // prepare fit3p input file, "input.dat" is the input file name fit3p_input = new
* File("fit3p/input.dat"); FileWriter fw = new FileWriter(fit3p_input); fw.write(result); fw.close(); } catch
* (IOException e) { System.out.println("Wrong input file for fit3p!"); System.out.println(e.getMessage());
* System.exit(0); } try { // system call for fit3p String[] command = {dir+ "/bin/fit3pbnd.exe"}; File runningDir = new
* File("fit3p"); Process fit = Runtime.getRuntime().exec(command, null, runningDir); int exitValue = fit.waitFor(); }
* catch (Exception e) { System.out.println("Error in run fit3p!"); System.out.println(e.getMessage()); System.exit(0);
* } // parse the output file from chemdis try { String fit3p_output = "fit3p/output.dat"; FileReader in = new
* FileReader(fit3p_output); BufferedReader data = new BufferedReader(in); String line =
* ChemParser.readMeaningfulLine(data); line = line.trim(); StringTokenizer st = new StringTokenizer(line); String A =
* st.nextToken(); String temp = st.nextToken(); temp = st.nextToken(); temp = st.nextToken(); double Ar =
* Double.parseDouble(temp); line = ChemParser.readMeaningfulLine(data); line = line.trim(); st = new
* StringTokenizer(line); String n = st.nextToken(); temp = st.nextToken(); temp = st.nextToken(); double nr =
* Double.parseDouble(temp); line = ChemParser.readMeaningfulLine(data); line = line.trim(); st = new
* StringTokenizer(line); String E = st.nextToken(); temp = st.nextToken(); temp = st.nextToken(); temp =
* st.nextToken(); double Er = Double.parseDouble(temp); if (Er < 0) { System.err.println(getStructure().toString());
* System.err.println("fitted Er < 0: "+Double.toString(Er)); double increase =
* Math.exp(-Er/GasConstant.getKcalMolK()/715.0); double deltan = Math.log(increase)/Math.log(715.0);
* System.err.println("n enlarged by factor of: " + Double.toString(deltan)); nr += deltan; Er = 0; } UncertainDouble
* udAr = new UncertainDouble(Ar, 0, "Adder"); UncertainDouble udnr = new UncertainDouble(nr, 0, "Adder");
* UncertainDouble udEr = new UncertainDouble(Er, 0, "Adder"); fittedReverseKinetics = new ArrheniusKinetics(udAr, udnr
* , udEr, "300-1500", 1, "fitting from forward and thermal",null); in.close(); } catch (Exception e) {
* System.out.println("Error in read output.dat from fit3p!"); System.out.println(e.getMessage()); System.exit(0); }
* return fittedReverseKinetics; //#] } //
*/
// ## operation fitReverseKineticsRoughly()
public void fitReverseKineticsRoughly() {
// #[ operation fitReverseKineticsRoughly()
// now is a rough fitting
if (isForward()) {
fittedReverseKinetics = null;
} else {
// double temp = 715;
double temp = 298.15; // 11/9/07 gmagoon: restored use of 298.15 per discussion with Sandeep
// double temp = Global.temperature.getK();
Kinetics[] k = getKinetics();
fittedReverseKinetics = new Kinetics[k.length];
double doubleAlpha;
for (int numKinetics = 0; numKinetics < k.length; numKinetics++) {
if (k[numKinetics] instanceof ArrheniusEPKinetics)
doubleAlpha = ((ArrheniusEPKinetics) k[numKinetics])
.getAlphaValue();
else
doubleAlpha = 0;
double Hrxn = calculateHrxn(new Temperature(temp, "K"));
double Srxn = calculateSrxn(new Temperature(temp, "K"));
// for EvansPolyani kinetics (Ea = Eo + alpha * Hrxn) remember that k.getEValue() gets Eo not Ea
// this Hrxn is for the reverse reaction (ie. -Hrxn_forward)
double doubleEr = k[numKinetics].getEValue()
- (doubleAlpha - 1) * Hrxn;
if (doubleEr < 0) {
Logger.warning("fitted Er < 0: "
+ Double.toString(doubleEr));
Logger.warning(getStructure().toString());
// doubleEr = 0;
}
UncertainDouble Er = new UncertainDouble(doubleEr,
k[numKinetics].getE().getUncertainty(), k[numKinetics]
.getE().getType());
UncertainDouble n = new UncertainDouble(0, 0, "Adder");
double doubleA = k[numKinetics].getAValue()
* Math.pow(temp, k[numKinetics].getNValue())
* Math.exp(Srxn / GasConstant.getCalMolK());
doubleA *= Math.pow(GasConstant.getCCAtmMolK() * temp,
-getStructure().getDeltaN()); // assumes Ideal gas law concentration and 1 Atm reference state
fittedReverseKinetics[numKinetics] = new ArrheniusKinetics(
new UncertainDouble(doubleA, 0, "Adder"), n, Er,
"300-1500", 1, "fitting from forward and thermal", null);
}
}
return;
// #]
}
/**
* Generates a reaction whose structure is opposite to that of the present reaction. Just appends the rate constant
* of this reaction to the reverse reaction.
*/
// ## operation generateReverseReaction()
public void generateReverseReaction() {
// #[ operation generateReverseReaction()
Structure s = getStructure();
// Kinetics k = getKinetics();
Kinetics[] k = kinetics;
if (kinetics == null)
throw new NullPointerException();
Structure newS = s.generateReverseStructure();
newS.setRedundancy(s.getRedundancy());
Reaction r = new Reaction(newS, k);
// if (hasAdditionalKinetics()){
// r.addAdditionalKinetics(additionalKinetics,1);
// }
r.setReverseReaction(this);
this.setReverseReaction(r);
return;
// #]
}
public String getComments() {
return comments;
}
// ## operation getDirection()
public int getDirection() {
// #[ operation getDirection()
return getStructure().getDirection();
// #]
}
// ## operation getFittedReverseKinetics()
public Kinetics[] getFittedReverseKinetics() {
// #[ operation getFittedReverseKinetics()
if (fittedReverseKinetics == null)
fitReverseKineticsRoughly();
return fittedReverseKinetics;
// #]
}
/*
* //## operation getForwardRateConstant() public Kinetics getForwardRateConstant() { //#[ operation
* getForwardRateConstant() if (isForward()) return kinetics; else return null; //#] }
*/
// ## operation getKinetics()
public Kinetics[] getKinetics() {
// #[ operation getKinetics()
// returns the kinetics OF THE FORWARD REACTION
// ie. if THIS is reverse, it calls this.getReverseReaction().getKinetics()
/*
* 29Jun2009-MRH: When getting kinetics, check whether it comes from a PRL or not. If so, return the kinetics.
* We are not worried about the redundancy because I assume the user inputs the Arrhenius kinetics for the
* overall reaction A = B + C E.g. CH4 = CH3 + H A n E The Arrhenius parameters would be for the overall
* decomposition of CH4, not for each carbon-hydrogen bond fission
*/
if (isFromPrimaryKineticLibrary()) {
return kinetics;
}
if (isForward()) {
int red = structure.getRedundancy();
if (red == 1)
return kinetics; // Don't waste time multiplying by 1
Kinetics[] kinetics2return = new Kinetics[kinetics.length];
for (int numKinetics = 0; numKinetics < kinetics.length; ++numKinetics) {
kinetics2return[numKinetics] = kinetics[numKinetics]
.multiply(red);
}
return kinetics2return;
} else if (isBackward()) {
Reaction rr = getReverseReaction();
// Added by MRH on 7/Sept/2009
// Required when reading in the restart files
if (rr == null) {
generateReverseReaction();
rr = getReverseReaction();
}
if (rr == null)
throw new NullPointerException("Reverse reaction is null.\n"
+ structure.toString());
if (!rr.isForward())
throw new InvalidReactionDirectionException(
structure.toString());
return rr.getKinetics();
} else
throw new InvalidReactionDirectionException(structure.toString());
}
public void setKineticsComments(String p_string, int num_k) {
kinetics[num_k].setComments(p_string);
}
// shamel: Added this function 6/10/2010, to get Kinetics Source to identify duplicates
// in Reaction Library, Seed Mech and Template Reaction with Library Reaction feature
public String getKineticsSource(int num_k) {
// The num_k is the number for different kinetics stored for one type of reaction but formed due to different
// families
// Returns Source as null when there are no Kinetics at all!
if (kinetics == null) {
return null;
}
String source = null;
if (kinetics[num_k] != null) {
source = kinetics[num_k].getSource();
}
// This is mostly done for case of H Abstraction where forward kinetic source may be null
if (source == null) {
try {
source = this.reverseReaction.kinetics[num_k].getSource();
} catch (NullPointerException e) {
// this catches several possibilities:
// this.reverseReaction == null
// this.reverseReaction.kinetics == null
// this.reverseReaction.kinetics[num_k] == null
source = null;
}
}
return source;
}
public void setKineticsSource(String p_string, int num_k) {
kinetics[num_k].setSource(p_string);
}
// ## operation getUpperBoundRate(Temperature)
public double getUpperBoundRate(Temperature p_temperature) {// svp
// #[ operation getUpperBoundRate(Temperature)
if (UpperBoundRate == 0.0) {
calculateUpperBoundRate(p_temperature);
}
return UpperBoundRate;
// #]
}
// ## operation getLowerBoundRate(Temperature)
public double getLowerBoundRate(Temperature p_temperature) {// svp
// #[ operation getLowerBoundRate(Temperature)
if (LowerBoundRate == 0.0) {
calculateLowerBoundRate(p_temperature);
}
return LowerBoundRate;
// #]
}
// ## operation getProductList()
public LinkedList getProductList() {
// #[ operation getProductList()
return structure.getProductList();
// #]
}
// ## operation getProductNumber()
public int getProductNumber() {
// #[ operation getProductNumber()
return getStructure().getProductNumber();
// #]
}
// ## operation getProducts()
public ListIterator getProducts() {
// #[ operation getProducts()
return structure.getProducts();
// #]
}
// ## operation getReactantList()
public LinkedList getReactantList() {
// #[ operation getReactantList()
return structure.getReactantList();
// #]
}
// ## operation getReactantNumber()
public int getReactantNumber() {
// #[ operation getReactantNumber()
return getStructure().getReactantNumber();
// #]
}
// ## operation getReactants()
public ListIterator getReactants() {
// #[ operation getReactants()
try {
return structure.getReactants();
} catch (RuntimeException e) {
Logger.critical("******DEBUGGING LINES FOLLOW******");
Logger.logStackTrace(e);
Logger.critical("This.toString:" + this.toString());
Logger.critical("Comments:" + comments);
Logger.critical("ChemkinString:" + ChemkinString);
Logger.critical("Rate constant:" + rateConstant);
Logger.critical("Finalized:" + finalized);
Logger.critical("KineticsFromPrimaryKineticLibrary:"
+ kineticsFromPrimaryKineticLibrary);
Logger.critical("ExpectDuplicate:" + expectDuplicate);
if (kinetics != null) {
Logger.critical("Kinetics size:" + kinetics.length);
Logger.critical("First kinetics info:" + kinetics[0].toString());
Logger.critical("First kinetics source:"
+ kinetics[0].getSource());
Logger.critical("First kinetics comment:"
+ kinetics[0].getComment());
}
if (fittedReverseKinetics != null) {
Logger.critical("Reverse kinetics size:"
+ fittedReverseKinetics.length);
Logger.critical("First reverse kinetics info:"
+ fittedReverseKinetics[0].toString());
Logger.critical("First reverse kinetics source:"
+ fittedReverseKinetics[0].getSource());
Logger.critical("First reverse kinetics comment:"
+ fittedReverseKinetics[0].getComment());
}
if (reverseReaction != null) {
Logger.critical("***Reverse reaction info below***");
Logger.critical("reverseReaction.toString:"
+ reverseReaction.toString());
Logger.critical("Comments:" + reverseReaction.comments);
Logger.critical("ChemkinString:"
+ reverseReaction.ChemkinString);
Logger.critical("Rate constant:" + reverseReaction.rateConstant);
Logger.critical("Finalized:" + reverseReaction.finalized);
Logger.critical("KineticsFromPrimaryKineticLibrary:"
+ reverseReaction.kineticsFromPrimaryKineticLibrary);
Logger.critical("ExpectDuplicate:"
+ reverseReaction.expectDuplicate);
if (reverseReaction.structure != null) {
Logger.critical("(for reverse reaction): structure.toString()"
+ reverseReaction.structure.toString());
}
if (reverseReaction.kinetics != null) {
Logger.critical("Kinetics size:"
+ reverseReaction.kinetics.length);
Logger.critical("First kinetics info:"
+ reverseReaction.kinetics[0].toString());
Logger.critical("First kinetics source:"
+ reverseReaction.kinetics[0].getSource());
Logger.critical("First kinetics comment:"
+ reverseReaction.kinetics[0].getComment());
}
if (reverseReaction.fittedReverseKinetics != null) {
Logger.critical("Reverse kinetics size:"
+ reverseReaction.fittedReverseKinetics.length);
Logger.critical("First reverse kinetics info:"
+ reverseReaction.fittedReverseKinetics[0]
.toString());
Logger.critical("First reverse kinetics source:"
+ reverseReaction.fittedReverseKinetics[0]
.getSource());
Logger.critical("First reverse kinetics comment:"
+ reverseReaction.fittedReverseKinetics[0]
.getComment());
}
}
Logger.flush();
throw e;
}
// #]
}
// ## operation getRedundancy()
public int getRedundancy() {
// #[ operation getRedundancy()
return getStructure().getRedundancy();
// #]
}
public void setRedundancy(int redundancy) {
getStructure().setRedundancy(redundancy);
}
public boolean hasResonanceIsomer() {
// #[ operation hasResonanceIsomer()
return (hasResonanceIsomerAsReactant() || hasResonanceIsomerAsProduct());
// #]
}
// ## operation hasResonanceIsomerAsProduct()
public boolean hasResonanceIsomerAsProduct() {
// #[ operation hasResonanceIsomerAsProduct()
for (Iterator iter = getProducts(); iter.hasNext();) {
Species spe = ((Species) iter.next());
if (spe.hasResonanceIsomers())
return true;
}
return false;
// #]
}
// ## operation hasResonanceIsomerAsReactant()
public boolean hasResonanceIsomerAsReactant() {
// #[ operation hasResonanceIsomerAsReactant()
for (Iterator iter = getReactants(); iter.hasNext();) {
Species spe = ((Species) iter.next());
if (spe.hasResonanceIsomers())
return true;
}
return false;
// #]
}
// ## operation hasReverseReaction()
public boolean hasReverseReaction() {
// #[ operation hasReverseReaction()
return reverseReaction != null;
// #]
}
// ## operation hashCode()
public int hashCode() {
// #[ operation hashCode()
// just use the structure's hashcode
return structure.hashCode();
// #]
}
// ## operation isDuplicated(Reaction)
/*
* public boolean isDuplicated(Reaction p_reaction) { //#[ operation isDuplicated(Reaction) // the same structure,
* return true Structure str1 = getStructure(); Structure str2 = p_reaction.getStructure(); //if
* (str1.isDuplicate(str2)) return true; // if not the same structure, check the resonance isomers if
* (!hasResonanceIsomer()) return false; if (str1.equals(str2)) return true; else return false; //#] }
*/
// ## operation isBackward()
public boolean isBackward() {
// #[ operation isBackward()
return structure.isBackward();
// #]
}
// ## operation isForward()
public boolean isForward() {
// #[ operation isForward()
return structure.isForward();
// #]
}
// ## operation isIncluded(LinkedHashSet)
public boolean isIncluded(LinkedHashSet p_speciesSet) {
// #[ operation isIncluded(LinkedHashSet)
return (allReactantsIncluded(p_speciesSet) && allProductsIncluded(p_speciesSet));
// #]
}
// ## operation makeReaction(Structure,Kinetics,boolean)
public static Reaction makeReaction(Structure p_structure,
Kinetics[] p_kinetics, boolean p_generateReverse) {
// #[ operation makeReaction(Structure,Kinetics,boolean)
if (!p_structure.repOk())
throw new InvalidStructureException(p_structure.toChemkinString(
false).toString());
for (int numKinetics = 0; numKinetics < p_kinetics.length; numKinetics++) {
if (!p_kinetics[numKinetics].repOk())
throw new InvalidKineticsException(
p_kinetics[numKinetics].toString());
}
Reaction r = new Reaction(p_structure, p_kinetics);
if (p_generateReverse) {
r.generateReverseReaction();
} else {
r.setReverseReaction(null);
}
return r;
// #]
}
// ## operation reactantEqualsProduct()
public boolean reactantEqualsProduct() {
// #[ operation reactantEqualsProduct()
return getStructure().reactantEqualsProduct();
// #]
}
// ## operation repOk()
public boolean repOk() {
// #[ operation repOk()
if (!structure.repOk()) {
Logger.error("Invalid Reaction Structure:" + structure.toString());
return false;
}
if (!isForward() && !isBackward()) {
Logger.error("Invalid Reaction Direction: "
+ String.valueOf(getDirection()));
return false;
}
if (isBackward() && reverseReaction == null) {
Logger.error("Backward Reaction without a reversed reaction defined!");
return false;
}
/*
* if (!getRateConstant().repOk()) { Logger.error("Invalid Rate Constant: " + getRateConstant().toString());
* return false; }
*/
Kinetics[] allKinetics = getKinetics();
if (allKinetics == null) return false;
for (int numKinetics = 0; numKinetics < allKinetics.length; ++numKinetics) {
if (!allKinetics[numKinetics].repOk()) {
Logger.error("Invalid Kinetics: "
+ allKinetics[numKinetics].toString());
return false;
}
}
if (!checkRateRange()) {
Logger.error("reaction rate is higher than the upper rate limit!");
Logger.info(getStructure().toString());
Temperature tup = new Temperature(1500, "K");
if (isForward()) {
Logger.info("k(T=1500) = "
+ String.valueOf(calculateTotalRate(tup)));
} else {
Logger.info("k(T=1500) = "
+ String.valueOf(calculateTotalRate(tup)));
Logger.info("Keq(T=1500) = "
+ String.valueOf(calculateKeq(tup)));
Logger.info("krev(T=1500) = "
+ String.valueOf(getReverseReaction()
.calculateTotalRate(tup)));
}
Logger.info(getKinetics().toString());
return false;
}
return true;
// #]
}
// ## operation setReverseReaction(Reaction)
public void setReverseReaction(Reaction p_reverseReaction) {
// #[ operation setReverseReaction(Reaction)
reverseReaction = p_reverseReaction;
if (p_reverseReaction != null)
reverseReaction.reverseReaction = this;
// #]
}
// ## operation toChemkinString()
public String toChemkinString(Temperature p_temperature) {
// #[ operation toChemkinString()
if (ChemkinString != null)
return ChemkinString;
StringBuilder result = new StringBuilder();
String strucString = String.format("%-52s", getStructure()
.toChemkinString(hasReverseReaction()));
Temperature stdtemp = new Temperature(298, "K");
double Hrxn = calculateHrxn(stdtemp);
Kinetics[] allKinetics = getKinetics();
for (int numKinetics = 0; numKinetics < allKinetics.length; ++numKinetics) {
String k = allKinetics[numKinetics].toChemkinString(Hrxn,
p_temperature, true);
if (allKinetics.length == 1)
result.append(strucString + " " + k);
else
result.append(strucString + " " + k + "\nDUP\n");
}
if (result.charAt(result.length() - 1) == '\n')
result.deleteCharAt(result.length() - 1);
ChemkinString = result.toString();
return result.toString();
}
public String toChemkinString(Temperature p_temperature, Pressure p_pressure) {
// For certain PDep cases it's helpful to be able to call this with a temperature and pressure
// but usually (and in this case) the pressure is irrelevant, so we just call the above
// toChemkinString(Temperature) method:
return toChemkinString(p_temperature);
}
public String toRestartString(Temperature p_temperature,
boolean pathReaction) {
/*
* Edited by MRH on 18Jan2010 Writing restart files was causing a bug in the RMG-generated chem.inp file For
* example, H+CH4=CH3+H2 in input file w/HXD13, CH4, and H2 RMG would correctly multiply the A factor by the
* structure's redundancy when calculating the rate to place in the ODEsolver input file. However, the A
* reported in the chem.inp file would be the "per event" A. This was due to the reaction.toChemkinString()
* method being called when writing the Restart coreReactions.txt and edgeReactions.txt files. At the first
* point of writing the chemkinString for this reaction (when it is still an edge reaction), RMG had not yet
* computed the redundancy of the structure (as H was not a core species at the time, but CH3 and H2 were). When
* RMG tried to write the chemkinString for the above reaction, using the correct redundancy, the chemkinString
* already existed and thus the toChemkinString() method was exited immediately. MRH is replacing the
* reaction.toChemkinString() call with reaction.toRestartString() when writing the Restart files, to account
* for this bug.
*/
String result = String.format("%-52s",
getStructure().toRestartString(hasReverseReaction())); // + " "+getStructure().direction +
// " "+getStructure().redundancy;
// MRH 18Jan2010: Restart files do not look for direction/redundancy
/*
* MRH 14Feb2010: Handle reactions with multiple kinetics
*/
String totalResult = "";
Kinetics[] allKinetics = getKinetics();
for (int numKinetics = 0; numKinetics < allKinetics.length; ++numKinetics) {
totalResult += result
+ " "
+ allKinetics[numKinetics].toChemkinString(
calculateHrxn(p_temperature), p_temperature, true);
if (allKinetics.length != 1) {
if (pathReaction) {
totalResult += "\n";
if (numKinetics != allKinetics.length - 1)
totalResult += getStructure().direction + "\t";
} else
totalResult += "\n\tDUP\n";
}
}
return totalResult;
}
/*
* MRH 23MAR2010: Method not used in RMG
*/
// //## operation toFullString()
// public String toFullString() {
// //#[ operation toFullString()
// return getStructure().toString() + getKinetics().toString() + getComments().toString();
//
//
//
// //#]
// }
// ## operation toString()
public String toString(Temperature p_temperature) {
// #[ operation toString()
String string2return = "";
Kinetics[] k = getKinetics();
for (int numKinetics = 0; numKinetics < k.length; ++numKinetics) {
string2return += getStructure().toString() + "\t";
string2return += k[numKinetics].toChemkinString(
calculateHrxn(p_temperature), p_temperature, false);
if (k.length > 1)
string2return += "\n";
}
return string2return;
}
/*
* MRH 23MAR2010: This method is redundant to toString()
*/
// 10/26/07 gmagoon: changed to take temperature as parameter (required changing function name from toString to
// reactionToString
// public String reactionToString(Temperature p_temperature) {
// // public String toString() {
// //#[ operation toString()
// // Temperature p_temperature = Global.temperature;
// Kinetics k = getKinetics();
// String kString = k.toChemkinString(calculateHrxn(p_temperature),p_temperature,false);
//
// return getStructure().toString() + '\t' + kString;
// //#]
// }
public static double getBIMOLECULAR_RATE_UPPER() {
return BIMOLECULAR_RATE_UPPER;
}
public static double getUNIMOLECULAR_RATE_UPPER() {
return UNIMOLECULAR_RATE_UPPER;
}
public void setComments(String p_comments) {
comments = p_comments;
}
/**
* Returns the reverse reaction of this reaction. If there is no reverse reaction present then a null object is
* returned.
*
* @return
*/
public Reaction getReverseReaction() {
return reverseReaction;
}
public void setKinetics(Kinetics p_kinetics, int k_index) {
if (p_kinetics == null) {
kinetics = null;
} else {
kinetics[k_index] = p_kinetics;
}
}
public void addAdditionalKinetics(Kinetics p_kinetics, int red,
boolean readingFromUserLibrary) {
if (finalized)
return;
if (p_kinetics == null)
return;
if (kinetics == null) {
kinetics = new Kinetics[1];
kinetics[0] = p_kinetics;
structure.redundancy = 1;
} else if (readingFromUserLibrary
|| (!readingFromUserLibrary && !p_kinetics
.isFromPrimaryKineticLibrary())) {
boolean kineticsAlreadyPresent = false;
for (int i = 0; i < kinetics.length; i++) {
Kinetics old_kinetics = kinetics[i];
if (!(old_kinetics instanceof ArrheniusKinetics))
continue; // we can't compare or increment
if (((ArrheniusKinetics) old_kinetics)
.equalNESource(p_kinetics)) {
((ArrheniusKinetics) old_kinetics).addToA(p_kinetics.getA()
.multiply((double) red));
kineticsAlreadyPresent = true;
}
}
if (!kineticsAlreadyPresent) {
Kinetics[] tempKinetics = kinetics;
kinetics = new Kinetics[tempKinetics.length + 1];
for (int i = 0; i < tempKinetics.length; i++) {
kinetics[i] = tempKinetics[i];
}
kinetics[kinetics.length - 1] = p_kinetics;
structure.redundancy = 1;
}
}
}
public void setFinalized(boolean p_finalized) {
finalized = p_finalized;
return;
}
public Structure getStructure() {
return structure;
}
public void setStructure(Structure p_Structure) {
structure = p_Structure;
}
/**
* Returns the reaction as an ASCII string.
*
* @return A string representing the reaction equation in ASCII test.
*/
@Override
public String toString() {
if (getReactantNumber() == 0 || getProductNumber() == 0)
return "";
String rxn = "";
Species species = (Species) structure.getReactantList().get(0);
rxn = rxn + species.getFullName();
for (int i = 1; i < getReactantNumber(); i++) {
species = (Species) structure.getReactantList().get(i);
rxn += " + " + species.getFullName();
}
rxn += " --> ";
species = (Species) structure.getProductList().get(0);
rxn = rxn + species.getFullName();
for (int i = 1; i < getProductNumber(); i++) {
species = (Species) structure.getProductList().get(i);
rxn += " + " + species.getFullName();
}
return rxn;
}
public String toInChIString() {
if (getReactantNumber() == 0 || getProductNumber() == 0)
return "";
String rxn = "";
Species species = (Species) structure.getReactantList().get(0);
rxn = rxn + species.getInChI();
for (int i = 1; i < getReactantNumber(); i++) {
species = (Species) structure.getReactantList().get(i);
rxn += " + " + species.getInChI();
}
rxn += " --> ";
species = (Species) structure.getProductList().get(0);
rxn = rxn + species.getInChI();
for (int i = 1; i < getProductNumber(); i++) {
species = (Species) structure.getProductList().get(i);
rxn += " + " + species.getInChI();
}
return rxn;
}
/**
* Calculates the flux of this reaction given the provided system snapshot. The system snapshot contains the
* temperature, pressure, and concentrations of each core species.
*
* @param ss
* The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateFlux(SystemSnapshot ss) {
return calculateForwardFlux(ss) - calculateReverseFlux(ss);
}
/**
* Calculates the forward flux of this reaction given the provided system snapshot. The system snapshot contains the
* temperature, pressure, and concentrations of each core species.
*
* @param ss
* The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateForwardFlux(SystemSnapshot ss) {
Temperature T = ss.getTemperature();
double forwardFlux = calculateTotalRate(T);
for (ListIterator<Species> iter = getReactants(); iter.hasNext();) {
Species spe = iter.next();
double conc = 0.0;
if (ss.getSpeciesStatus(spe) != null)
conc = ss.getSpeciesStatus(spe).getConcentration();
if (conc < 0) {
double aTol = ReactionModelGenerator.getAtol();
// if (Math.abs(conc) < aTol) conc = 0;
// else throw new NegativeConcentrationException(spe.getFullName() + ": " + String.valueOf(conc));
if (conc < -100.0 * aTol)
throw new NegativeConcentrationException("Species "
+ spe.getFullName()
+ " has negative concentration: "
+ String.valueOf(conc));
}
forwardFlux *= conc;
}
return forwardFlux;
}
/**
* Calculates the flux of this reaction given the provided system snapshot. The system snapshot contains the
* temperature, pressure, and concentrations of each core species.
*
* @param ss
* The system snapshot at which to determine the reaction flux
* @return The determined reaction flux
*/
public double calculateReverseFlux(SystemSnapshot ss) {
if (hasReverseReaction())
return reverseReaction.calculateForwardFlux(ss);
else
return 0.0;
}
public boolean isFromPrimaryKineticLibrary() {
return kineticsFromPrimaryKineticLibrary;
}
public void setIsFromPrimaryKineticLibrary(boolean p_boolean) {
kineticsFromPrimaryKineticLibrary = p_boolean;
if (reverseReaction != null) {
reverseReaction.kineticsFromPrimaryKineticLibrary = p_boolean;
}
}
public boolean hasMultipleKinetics() {
if (getKinetics().length > 1)
return true;
else
return false;
}
public void setExpectDuplicate(boolean b) {
expectDuplicate = b;
}
public boolean getExpectDuplicate() {
return expectDuplicate;
}
public void prune() {
// Do what's necessary to prune the reaction
// Also clears the reverse, so don't expect to be able to get it back
// Do santy check on the isFromPrimaryKineticLibrary() method we rely on.
// (This shouldn't be necessary, but we have no unit test framework so I'm building one in here!)
if (!isFromPrimaryKineticLibrary()) {
if (isForward())
if (getKineticsSource(0) != null)
if (getKineticsSource(0).contains("Library"))
throw new RuntimeException(
String.format(
"Reaction %s kinetics source contains 'Library' but isFromPrimaryKineticLibrary() returned false.",
this));
if (isBackward())
if (getReverseReaction().getKineticsSource(0) != null)
if (getReverseReaction().getKineticsSource(0).contains(
"Library"))
throw new RuntimeException(
String.format(
"Reverse of reaction %s kinetics source contains 'Library' but isFromPrimaryKineticLibrary() returned false.",
this));
// I'm not sure why we can't clear the reverse anyway - as long as the direction WITH kinetics still has a
// Structure we should be ok.
}
// Use isFromPrimaryKineticLibrary() to decide if it's safe to clear the reaction structure
if (!isFromPrimaryKineticLibrary()) {
setStructure(null);
setReverseReaction(null);
}
}
/**
* Return the total number of atoms in the reactants (and products).
*/
public int getAtomNumber() {
int atoms = 0;
for (ListIterator<Species> iter = getReactants(); iter.hasNext();) {
Species spe = iter.next();
atoms += spe.getChemGraph().getAtomNumber();
}
return atoms;
}
}
/*********************************************************************
* File Path : RMG\RMG\jing\rxn\Reaction.java
*********************************************************************/
| true | true | public double calculateTotalRate(Temperature p_temperature) {
double rate = 0;
Temperature stdtemp = new Temperature(298, "K");
double Hrxn = calculateHrxn(stdtemp);
Temperature sys_temp = ReactionModelGenerator.getTemp4BestKinetics();
/*
* AJ 12JULY2010: Added diffusive limits from previous RMG version by replacing function calculateTotalRate
* Checks the exothermicity and molecularity of reaction to determine the diffusive rate limit
*/
/*
* 29Jun2009-MRH: Added a kinetics from PRL check If the kinetics for this reaction is from a PRL, use those
* numbers to compute the rate. Else, proceed as before.
*/
/*
* MRH 18MAR2010: Changing the structure of a reaction's kinetics If the kinetics are from a primary kinetic
* library, we assume the user has supplied the total pre-exponential factor for the reaction (and not the
* per-event pre-exponential facor). If the kinetics were estimated by RMG, the pre-exponential factor must be
* multiplied by the "redundancy" (# of events)
*/
if (kineticsFromPrimaryKineticLibrary) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
rate += k.calculateRate(p_temperature, Hrxn);
}
return rate;
} else if (isForward()) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
if ((int) structure.redundancy != 1) {
k = k.multiply(structure.redundancy);
}
rate += k.calculateRate(p_temperature, Hrxn);
}
/*
* Diffusion limits added by AJ on July 12, 2010 Requires correction in the forward direction only, reverse
* reaction corrects itself If ReactionModelGenerator.useDiffusion is true (solvation is on) compute kd and
* return keff
*/
if (ReactionModelGenerator.getUseDiffusion()) {
int numReacts = structure.getReactantNumber();
int numProds = structure.getProductNumber();
double keff = 0.0;
double DiffFactor = 0.0;
if (numReacts == 1 && numProds == 1) {
keff = rate;
rate = keff;
DiffFactor = 1;
} else if (numReacts == 1 && numProds == 2) {
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 1) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 2) {
double rxn_Keq = structure.calculateKeq(p_temperature);
double deltaHrxn = structure.calculateHrxn(p_temperature);
if (rxn_Keq > 1) { // Forward reaction is exothermic hence the corresponding diffusion limit applies
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (rxn_Keq < 1) { // Reverse reaction is exothermic and the corresponding diffusion limit
// should be used
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
}
} else if (numReacts == 2 && numProds == 3) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 4) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
}
// Add comments only if the temperature at which the function has been called corresponds to the system
// temperature specified in the condition file
// And if they haven't already been added
if (p_temperature.getK() == sys_temp.getK()) {
String oldComments = k_All[0].getComment();
if (!oldComments.contains("Diffusion")) {
if (numReacts == 1 && numProds == 1)
oldComments += " Unimolecular: no diffusion limitation.";
String newComments = oldComments
+ String.format(
" Diffusion factor=%.3g, rate=%.3g, Keq=%.3g, at T=%.0fK.",
DiffFactor, rate,
calculateKeq(p_temperature),
p_temperature.getK());
setKineticsComments(newComments, 0);
}
}
}
return rate;
} else if (isBackward()) {
Reaction r = getReverseReaction();
rate = r.calculateTotalRate(p_temperature);
return rate * calculateKeq(p_temperature);
} else {
throw new InvalidReactionDirectionException();
}
}
| public double calculateTotalRate(Temperature p_temperature) {
double rate = 0;
Temperature stdtemp = new Temperature(298, "K");
double Hrxn = calculateHrxn(stdtemp);
Temperature sys_temp = ReactionModelGenerator.getTemp4BestKinetics();
/*
* AJ 12JULY2010: Added diffusive limits from previous RMG version by replacing function calculateTotalRate
* Checks the exothermicity and molecularity of reaction to determine the diffusive rate limit
*/
/*
* 29Jun2009-MRH: Added a kinetics from PRL check If the kinetics for this reaction is from a PRL, use those
* numbers to compute the rate. Else, proceed as before.
*/
/*
* MRH 18MAR2010: Changing the structure of a reaction's kinetics If the kinetics are from a primary kinetic
* library, we assume the user has supplied the total pre-exponential factor for the reaction (and not the
* per-event pre-exponential facor). If the kinetics were estimated by RMG, the pre-exponential factor must be
* multiplied by the "redundancy" (# of events)
*/
if (kineticsFromPrimaryKineticLibrary) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
rate += k.calculateRate(p_temperature, Hrxn);
}
if(isBackward()){
rate = rate * calculateKeq(p_temperature);
}
return rate;
} else if (isForward()) {
Kinetics[] k_All = kinetics;
for (int numKinetics = 0; numKinetics < kinetics.length; numKinetics++) {
Kinetics k = k_All[numKinetics];
if ((int) structure.redundancy != 1) {
k = k.multiply(structure.redundancy);
}
rate += k.calculateRate(p_temperature, Hrxn);
}
/*
* Diffusion limits added by AJ on July 12, 2010 Requires correction in the forward direction only, reverse
* reaction corrects itself If ReactionModelGenerator.useDiffusion is true (solvation is on) compute kd and
* return keff
*/
if (ReactionModelGenerator.getUseDiffusion()) {
int numReacts = structure.getReactantNumber();
int numProds = structure.getProductNumber();
double keff = 0.0;
double DiffFactor = 0.0;
if (numReacts == 1 && numProds == 1) {
keff = rate;
rate = keff;
DiffFactor = 1;
} else if (numReacts == 1 && numProds == 2) {
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 1) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 2) {
double rxn_Keq = structure.calculateKeq(p_temperature);
double deltaHrxn = structure.calculateHrxn(p_temperature);
if (rxn_Keq > 1) { // Forward reaction is exothermic hence the corresponding diffusion limit applies
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (rxn_Keq < 1) { // Reverse reaction is exothermic and the corresponding diffusion limit
// should be used
double k_back = rate / calculateKeq(p_temperature);
LinkedList reactantsInBackRxn = structure.products;
double k_back_diff = calculatediff(reactantsInBackRxn);
double k_back_eff = k_back * k_back_diff
/ (k_back + k_back_diff);
keff = k_back_eff * calculateKeq(p_temperature);
DiffFactor = keff / rate;
rate = keff;
}
} else if (numReacts == 2 && numProds == 3) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
} else if (numReacts == 2 && numProds == 4) {
double k_forw = rate;
LinkedList reactantsInForwRxn = structure.reactants;
double k_forw_diff = calculatediff(reactantsInForwRxn);
double k_forw_eff = k_forw * k_forw_diff
/ (k_forw + k_forw_diff);
keff = k_forw_eff;
DiffFactor = keff / rate;
rate = keff;
}
// Add comments only if the temperature at which the function has been called corresponds to the system
// temperature specified in the condition file
// And if they haven't already been added
if (p_temperature.getK() == sys_temp.getK()) {
String oldComments = k_All[0].getComment();
if (!oldComments.contains("Diffusion")) {
if (numReacts == 1 && numProds == 1)
oldComments += " Unimolecular: no diffusion limitation.";
String newComments = oldComments
+ String.format(
" Diffusion factor=%.3g, rate=%.3g, Keq=%.3g, at T=%.0fK.",
DiffFactor, rate,
calculateKeq(p_temperature),
p_temperature.getK());
setKineticsComments(newComments, 0);
}
}
}
return rate;
} else if (isBackward()) {
Reaction r = getReverseReaction();
rate = r.calculateTotalRate(p_temperature);
return rate * calculateKeq(p_temperature);
} else {
throw new InvalidReactionDirectionException();
}
}
|
diff --git a/src/openblocks/client/renderer/tileentity/TileEntityAutoEnchantmentTableRenderer.java b/src/openblocks/client/renderer/tileentity/TileEntityAutoEnchantmentTableRenderer.java
index 7064e329..0a5538e6 100644
--- a/src/openblocks/client/renderer/tileentity/TileEntityAutoEnchantmentTableRenderer.java
+++ b/src/openblocks/client/renderer/tileentity/TileEntityAutoEnchantmentTableRenderer.java
@@ -1,79 +1,77 @@
package openblocks.client.renderer.tileentity;
import net.minecraft.client.model.ModelBook;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import openblocks.OpenBlocks;
import openblocks.common.tileentity.TileEntityAutoEnchantmentTable;
import org.lwjgl.opengl.GL11;
public class TileEntityAutoEnchantmentTableRenderer extends
TileEntitySpecialRenderer {
private static final ResourceLocation enchantingTableBookTextures = new ResourceLocation("textures/entity/enchanting_table_book.png");
private ModelBook enchantmentBook = new ModelBook();
@Override
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
TileEntityAutoEnchantmentTable table = (TileEntityAutoEnchantmentTable)tileentity;
GL11.glPushMatrix();
bindTexture(TextureMap.locationBlocksTexture);
GL11.glTranslatef((float)x, (float)y, (float)z);
- GL11.glDisable(GL11.GL_LIGHTING);
OpenRenderHelper.renderCube(0, 0, 0, 1, 0.75, 1, OpenBlocks.Blocks.autoEnchantmentTable, null);
- GL11.glEnable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glTranslatef((float)x + 0.5F, (float)y + 0.75F, (float)z + 0.5F);
float f1 = table.tickCount + f;
GL11.glTranslatef(0.0F, 0.1F + MathHelper.sin(f1 * 0.1F) * 0.01F, 0.0F);
float f2;
for (f2 = table.bookRotation2 - table.bookRotationPrev; f2 >= (float)Math.PI; f2 -= ((float)Math.PI * 2F)) {
;
}
while (f2 < -(float)Math.PI) {
f2 += ((float)Math.PI * 2F);
}
float f3 = table.bookRotationPrev + f2 * f;
GL11.glRotatef(-f3 * 180.0F / (float)Math.PI, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(80.0F, 0.0F, 0.0F, 1.0F);
bindTexture(enchantingTableBookTextures);
float f4 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.25F;
float f5 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.75F;
f4 = (f4 - MathHelper.truncateDoubleToInt(f4)) * 1.6F - 0.3F;
f5 = (f5 - MathHelper.truncateDoubleToInt(f5)) * 1.6F - 0.3F;
if (f4 < 0.0F) {
f4 = 0.0F;
}
if (f5 < 0.0F) {
f5 = 0.0F;
}
if (f4 > 1.0F) {
f4 = 1.0F;
}
if (f5 > 1.0F) {
f5 = 1.0F;
}
float f6 = table.bookSpreadPrev + (table.bookSpread - table.bookSpreadPrev) * f;
GL11.glEnable(GL11.GL_CULL_FACE);
this.enchantmentBook.render((Entity)null, f1, f4, f5, f6, 0.0F, 0.0625F);
GL11.glPopMatrix();
GL11.glColor4f(1, 1, 1, 1);
}
}
| false | true | public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
TileEntityAutoEnchantmentTable table = (TileEntityAutoEnchantmentTable)tileentity;
GL11.glPushMatrix();
bindTexture(TextureMap.locationBlocksTexture);
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glDisable(GL11.GL_LIGHTING);
OpenRenderHelper.renderCube(0, 0, 0, 1, 0.75, 1, OpenBlocks.Blocks.autoEnchantmentTable, null);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glTranslatef((float)x + 0.5F, (float)y + 0.75F, (float)z + 0.5F);
float f1 = table.tickCount + f;
GL11.glTranslatef(0.0F, 0.1F + MathHelper.sin(f1 * 0.1F) * 0.01F, 0.0F);
float f2;
for (f2 = table.bookRotation2 - table.bookRotationPrev; f2 >= (float)Math.PI; f2 -= ((float)Math.PI * 2F)) {
;
}
while (f2 < -(float)Math.PI) {
f2 += ((float)Math.PI * 2F);
}
float f3 = table.bookRotationPrev + f2 * f;
GL11.glRotatef(-f3 * 180.0F / (float)Math.PI, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(80.0F, 0.0F, 0.0F, 1.0F);
bindTexture(enchantingTableBookTextures);
float f4 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.25F;
float f5 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.75F;
f4 = (f4 - MathHelper.truncateDoubleToInt(f4)) * 1.6F - 0.3F;
f5 = (f5 - MathHelper.truncateDoubleToInt(f5)) * 1.6F - 0.3F;
if (f4 < 0.0F) {
f4 = 0.0F;
}
if (f5 < 0.0F) {
f5 = 0.0F;
}
if (f4 > 1.0F) {
f4 = 1.0F;
}
if (f5 > 1.0F) {
f5 = 1.0F;
}
float f6 = table.bookSpreadPrev + (table.bookSpread - table.bookSpreadPrev) * f;
GL11.glEnable(GL11.GL_CULL_FACE);
this.enchantmentBook.render((Entity)null, f1, f4, f5, f6, 0.0F, 0.0625F);
GL11.glPopMatrix();
GL11.glColor4f(1, 1, 1, 1);
}
| public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
TileEntityAutoEnchantmentTable table = (TileEntityAutoEnchantmentTable)tileentity;
GL11.glPushMatrix();
bindTexture(TextureMap.locationBlocksTexture);
GL11.glTranslatef((float)x, (float)y, (float)z);
OpenRenderHelper.renderCube(0, 0, 0, 1, 0.75, 1, OpenBlocks.Blocks.autoEnchantmentTable, null);
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glTranslatef((float)x + 0.5F, (float)y + 0.75F, (float)z + 0.5F);
float f1 = table.tickCount + f;
GL11.glTranslatef(0.0F, 0.1F + MathHelper.sin(f1 * 0.1F) * 0.01F, 0.0F);
float f2;
for (f2 = table.bookRotation2 - table.bookRotationPrev; f2 >= (float)Math.PI; f2 -= ((float)Math.PI * 2F)) {
;
}
while (f2 < -(float)Math.PI) {
f2 += ((float)Math.PI * 2F);
}
float f3 = table.bookRotationPrev + f2 * f;
GL11.glRotatef(-f3 * 180.0F / (float)Math.PI, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(80.0F, 0.0F, 0.0F, 1.0F);
bindTexture(enchantingTableBookTextures);
float f4 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.25F;
float f5 = table.pageFlipPrev + (table.pageFlip - table.pageFlipPrev)
* f + 0.75F;
f4 = (f4 - MathHelper.truncateDoubleToInt(f4)) * 1.6F - 0.3F;
f5 = (f5 - MathHelper.truncateDoubleToInt(f5)) * 1.6F - 0.3F;
if (f4 < 0.0F) {
f4 = 0.0F;
}
if (f5 < 0.0F) {
f5 = 0.0F;
}
if (f4 > 1.0F) {
f4 = 1.0F;
}
if (f5 > 1.0F) {
f5 = 1.0F;
}
float f6 = table.bookSpreadPrev + (table.bookSpread - table.bookSpreadPrev) * f;
GL11.glEnable(GL11.GL_CULL_FACE);
this.enchantmentBook.render((Entity)null, f1, f4, f5, f6, 0.0F, 0.0625F);
GL11.glPopMatrix();
GL11.glColor4f(1, 1, 1, 1);
}
|
diff --git a/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java b/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
index d89d88875..20f75829b 100644
--- a/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
+++ b/modules/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ContentItemsSource.java
@@ -1,180 +1,183 @@
package org.apache.lucene.benchmark.byTask.feeds;
/**
* 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.
*/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.lucene.benchmark.byTask.utils.Config;
import org.apache.lucene.benchmark.byTask.utils.Format;
/**
* Base class for source of data for benchmarking
* <p>
* Keeps track of various statistics, such as how many data items were generated,
* size in bytes etc.
* <p>
* Supports the following configuration parameters:
* <ul>
* <li><b>content.source.forever</b> - specifies whether to generate items
* forever (<b>default=true</b>).
* <li><b>content.source.verbose</b> - specifies whether messages should be
* output by the content source (<b>default=false</b>).
* <li><b>content.source.encoding</b> - specifies which encoding to use when
* reading the files of that content source. Certain implementations may define
* a default value if this parameter is not specified. (<b>default=null</b>).
* <li><b>content.source.log.step</b> - specifies for how many items a
* message should be logged. If set to 0 it means no logging should occur.
* <b>NOTE:</b> if verbose is set to false, logging should not occur even if
* logStep is not 0 (<b>default=0</b>).
* </ul>
*/
public abstract class ContentItemsSource {
private long bytesCount;
private long totalBytesCount;
private int itemCount;
private int totalItemCount;
private Config config;
private int lastPrintedNumUniqueTexts = 0;
private long lastPrintedNumUniqueBytes = 0;
private int printNum = 0;
protected boolean forever;
protected int logStep;
protected boolean verbose;
protected String encoding;
/** update count of bytes generated by this source */
protected final synchronized void addBytes(long numBytes) {
bytesCount += numBytes;
totalBytesCount += numBytes;
}
/** update count of items generated by this source */
protected final synchronized void addItem() {
++itemCount;
++totalItemCount;
}
/**
* A convenience method for collecting all the files of a content source from
* a given directory. The collected {@link File} instances are stored in the
* given <code>files</code>.
*/
protected final void collectFiles(File dir, ArrayList<File> files) {
if (!dir.canRead()) {
return;
}
File[] dirFiles = dir.listFiles();
Arrays.sort(dirFiles);
for (int i = 0; i < dirFiles.length; i++) {
File file = dirFiles[i];
if (file.isDirectory()) {
collectFiles(file, files);
} else if (file.canRead()) {
files.add(file);
}
}
}
/**
* Returns true whether it's time to log a message (depending on verbose and
* the number of items generated).
*/
protected final boolean shouldLog() {
return verbose && logStep > 0 && itemCount % logStep == 0;
}
/** Called when reading from this content source is no longer required. */
public abstract void close() throws IOException;
/** Returns the number of bytes generated since last reset. */
public final long getBytesCount() { return bytesCount; }
/** Returns the number of generated items since last reset. */
public final int getItemsCount() { return itemCount; }
public final Config getConfig() { return config; }
/** Returns the total number of bytes that were generated by this source. */
public final long getTotalBytesCount() { return totalBytesCount; }
/** Returns the total number of generated items. */
public final int getTotalItemsCount() { return totalItemCount; }
/**
* Resets the input for this content source, so that the test would behave as
* if it was just started, input-wise.
* <p>
* <b>NOTE:</b> the default implementation resets the number of bytes and
* items generated since the last reset, so it's important to call
* super.resetInputs in case you override this method.
*/
@SuppressWarnings("unused")
public void resetInputs() throws IOException {
bytesCount = 0;
itemCount = 0;
}
/**
* Sets the {@link Config} for this content source. If you override this
* method, you must call super.setConfig.
*/
public void setConfig(Config config) {
this.config = config;
forever = config.get("content.source.forever", true);
logStep = config.get("content.source.log.step", 0);
verbose = config.get("content.source.verbose", false);
encoding = config.get("content.source.encoding", null);
}
public void printStatistics(String itemsName) {
+ if (!verbose) {
+ return;
+ }
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
}
| true | true | public void printStatistics(String itemsName) {
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
| public void printStatistics(String itemsName) {
if (!verbose) {
return;
}
boolean print = false;
String col = " ";
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append("------------> ").append(getClass().getSimpleName()).append(" statistics (").append(printNum).append("): ").append(newline);
int nut = getTotalItemsCount();
if (nut > lastPrintedNumUniqueTexts) {
print = true;
sb.append("total count of "+itemsName+": ").append(Format.format(0,nut,col)).append(newline);
lastPrintedNumUniqueTexts = nut;
}
long nub = getTotalBytesCount();
if (nub > lastPrintedNumUniqueBytes) {
print = true;
sb.append("total bytes of "+itemsName+": ").append(Format.format(0,nub,col)).append(newline);
lastPrintedNumUniqueBytes = nub;
}
if (getItemsCount() > 0) {
print = true;
sb.append("num "+itemsName+" added since last inputs reset: ").append(Format.format(0,getItemsCount(),col)).append(newline);
sb.append("total bytes added for "+itemsName+" since last inputs reset: ").append(Format.format(0,getBytesCount(),col)).append(newline);
}
if (print) {
System.out.println(sb.append(newline).toString());
printNum++;
}
}
|
diff --git a/src/org/ice/io/Mouse.java b/src/org/ice/io/Mouse.java
index a1632a6..92b1d6d 100644
--- a/src/org/ice/io/Mouse.java
+++ b/src/org/ice/io/Mouse.java
@@ -1,51 +1,51 @@
package org.ice.io;
import java.awt.GraphicsDevice;
/**
* User-friendly mouse class. Uses MouseDriver and only exposes methods needed by engine.
*
* @author home
*
*/
public class Mouse {
public static enum MouseClick { NONE, LEFT, RIGHT, WHEEL };
private MouseDriver mouseDriver;
public Mouse( GraphicsDevice graphicsDevice )
{
this.mouseDriver = new MouseDriver();
graphicsDevice.getFullScreenWindow().addMouseListener( mouseDriver );
graphicsDevice.getFullScreenWindow().addMouseMotionListener( mouseDriver );
}
public MouseClick getMouseButton()
{
- final int button = mouseDriver.getMouseButton();
+ int button = mouseDriver.getMouseButton();
switch(button)
{
case 0:
return MouseClick.NONE;
case 1:
return MouseClick.LEFT;
case 2:
return MouseClick.WHEEL;
case 3:
return MouseClick.RIGHT;
}
return MouseClick.NONE;
}
public int getMouseX()
{
return mouseDriver.getMouseX();
}
public int getMouseY()
{
return mouseDriver.getMouseY();
}
}
| true | true | public MouseClick getMouseButton()
{
final int button = mouseDriver.getMouseButton();
switch(button)
{
case 0:
return MouseClick.NONE;
case 1:
return MouseClick.LEFT;
case 2:
return MouseClick.WHEEL;
case 3:
return MouseClick.RIGHT;
}
return MouseClick.NONE;
}
| public MouseClick getMouseButton()
{
int button = mouseDriver.getMouseButton();
switch(button)
{
case 0:
return MouseClick.NONE;
case 1:
return MouseClick.LEFT;
case 2:
return MouseClick.WHEEL;
case 3:
return MouseClick.RIGHT;
}
return MouseClick.NONE;
}
|
diff --git a/src/cz/cuni/mff/peckam/java/origamist/gui/listing/ListingTreeSelectionListener.java b/src/cz/cuni/mff/peckam/java/origamist/gui/listing/ListingTreeSelectionListener.java
index 698571e..57475dd 100644
--- a/src/cz/cuni/mff/peckam/java/origamist/gui/listing/ListingTreeSelectionListener.java
+++ b/src/cz/cuni/mff/peckam/java/origamist/gui/listing/ListingTreeSelectionListener.java
@@ -1,88 +1,89 @@
/**
*
*/
package cz.cuni.mff.peckam.java.origamist.gui.listing;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import cz.cuni.mff.peckam.java.origamist.exceptions.UnsupportedDataFormatException;
import cz.cuni.mff.peckam.java.origamist.files.File;
import cz.cuni.mff.peckam.java.origamist.gui.viewer.OrigamiViewer;
import cz.cuni.mff.peckam.java.origamist.model.Origami;
import cz.cuni.mff.peckam.java.origamist.services.ServiceLocator;
/**
* Listens for the selections of model files and displays them in the main area.
*
* @author Martin Pecka
*/
public class ListingTreeSelectionListener implements TreeSelectionListener
{
@Override
public void valueChanged(final TreeSelectionEvent e)
{
if (!e.isAddedPath()) {
return;
}
final Object selected = ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject();
if (selected instanceof File) {
final OrigamiViewer viewer = ServiceLocator.get(OrigamiViewer.class);
if (viewer == null) {
Logger.getLogger("application").log(Level.ERROR,
"Cannot use ListingTreeSelectionListener when not using OrigamiViewer");
} else {
final File file = (File) selected;
final ListingTree tree = (ListingTree) e.getSource();
file.addPropertyChangeListener("isOrigamiLoaded", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
file.fillFromOrigami();
- tree.invalidate();
+ tree.revalidate();
+ tree.repaint(tree.getRowBounds(tree.getRowForPath(e.getPath())));
}
});
}
});
// load the origami in a separate thread, it may take a long time
new Thread() {
@Override
public void run()
{
try {
final Origami origami = file.getOrigami();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
viewer.setDisplayedOrigami(origami);
}
});
} catch (UnsupportedDataFormatException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
} catch (IOException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
}
}
}.start();
}
}
}
}
| true | true | public void valueChanged(final TreeSelectionEvent e)
{
if (!e.isAddedPath()) {
return;
}
final Object selected = ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject();
if (selected instanceof File) {
final OrigamiViewer viewer = ServiceLocator.get(OrigamiViewer.class);
if (viewer == null) {
Logger.getLogger("application").log(Level.ERROR,
"Cannot use ListingTreeSelectionListener when not using OrigamiViewer");
} else {
final File file = (File) selected;
final ListingTree tree = (ListingTree) e.getSource();
file.addPropertyChangeListener("isOrigamiLoaded", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
file.fillFromOrigami();
tree.invalidate();
}
});
}
});
// load the origami in a separate thread, it may take a long time
new Thread() {
@Override
public void run()
{
try {
final Origami origami = file.getOrigami();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
viewer.setDisplayedOrigami(origami);
}
});
} catch (UnsupportedDataFormatException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
} catch (IOException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
}
}
}.start();
}
}
}
| public void valueChanged(final TreeSelectionEvent e)
{
if (!e.isAddedPath()) {
return;
}
final Object selected = ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject();
if (selected instanceof File) {
final OrigamiViewer viewer = ServiceLocator.get(OrigamiViewer.class);
if (viewer == null) {
Logger.getLogger("application").log(Level.ERROR,
"Cannot use ListingTreeSelectionListener when not using OrigamiViewer");
} else {
final File file = (File) selected;
final ListingTree tree = (ListingTree) e.getSource();
file.addPropertyChangeListener("isOrigamiLoaded", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
file.fillFromOrigami();
tree.revalidate();
tree.repaint(tree.getRowBounds(tree.getRowForPath(e.getPath())));
}
});
}
});
// load the origami in a separate thread, it may take a long time
new Thread() {
@Override
public void run()
{
try {
final Origami origami = file.getOrigami();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
viewer.setDisplayedOrigami(origami);
}
});
} catch (UnsupportedDataFormatException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
} catch (IOException e1) {
Logger.getLogger("viewer").l7dlog(Level.ERROR, "modelLazyLoadException", e1);
}
}
}.start();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.