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/command/CommandArgs.java b/command/CommandArgs.java
index 69b82d2..5f8ef80 100644
--- a/command/CommandArgs.java
+++ b/command/CommandArgs.java
@@ -1,99 +1,100 @@
package fr.aumgn.bukkitutils.command;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import fr.aumgn.bukkitutils.command.exception.ArgNotAValidNumber;
import fr.aumgn.bukkitutils.command.exception.CommandUsageError;
import fr.aumgn.bukkitutils.command.messages.Messages;
public class CommandArgs {
private Messages local;
private Set<Character> flags;
private String[] args;
public CommandArgs(Messages local, String[] tokens, Set<Character> allowedFlag, int min, int max) {
this.local = local;
flags = new HashSet<Character>();
List<String> argsList = new ArrayList<String>(tokens.length);
for (String token : tokens) {
if (token.isEmpty()) {
// Do nothing
- } else if (token.charAt(0) == '-' && token.length() > 1) {
+ } else if (token.charAt(0) == '-' && token.length() > 1
+ && Character.isLetter(token.charAt(1))) {
for (char flag : token.substring(1).toCharArray()) {
if (!allowedFlag.contains(flag)) {
throw new CommandUsageError(String.format(local.invalidFlag(), flag));
}
flags.add(flag);
}
} else {
argsList.add(token);
}
}
if (argsList.size() < min) {
throw new CommandUsageError(String.format(local.missingArguments(),
argsList.size(), min));
}
if (max != -1 && argsList.size() > max) {
throw new CommandUsageError(String.format(local.tooManyArguments(),
argsList.size(), max));
}
args = argsList.toArray(new String[0]);
}
public boolean hasFlags() {
return !flags.isEmpty();
}
public boolean hasFlag(char character) {
return flags.contains(character);
}
public int length() {
return args.length;
}
public String get(int index) {
return args[index];
}
public int getInteger(int index) {
try {
return Integer.parseInt(get(index));
} catch (NumberFormatException exc) {
throw new ArgNotAValidNumber(
String.format(local.notAValidNumber(), index + 1));
}
}
public double getDouble(int index) {
try {
return Double.parseDouble(get(index));
} catch (NumberFormatException exc) {
throw new ArgNotAValidNumber(
String.format(local.notAValidNumber(), index + 1));
}
}
public String get(int index, int endIndex) {
StringBuilder builder = new StringBuilder();
for (int i = index; i < endIndex; i++) {
builder.append(args[i]);
builder.append(" ");
}
builder.append(args[endIndex]);
return builder.toString();
}
public List<String> asList() {
return Arrays.asList(args);
}
public List<String> asList(int index, int endIndex) {
return asList().subList(index, endIndex);
}
}
| true | true | public CommandArgs(Messages local, String[] tokens, Set<Character> allowedFlag, int min, int max) {
this.local = local;
flags = new HashSet<Character>();
List<String> argsList = new ArrayList<String>(tokens.length);
for (String token : tokens) {
if (token.isEmpty()) {
// Do nothing
} else if (token.charAt(0) == '-' && token.length() > 1) {
for (char flag : token.substring(1).toCharArray()) {
if (!allowedFlag.contains(flag)) {
throw new CommandUsageError(String.format(local.invalidFlag(), flag));
}
flags.add(flag);
}
} else {
argsList.add(token);
}
}
if (argsList.size() < min) {
throw new CommandUsageError(String.format(local.missingArguments(),
argsList.size(), min));
}
if (max != -1 && argsList.size() > max) {
throw new CommandUsageError(String.format(local.tooManyArguments(),
argsList.size(), max));
}
args = argsList.toArray(new String[0]);
}
| public CommandArgs(Messages local, String[] tokens, Set<Character> allowedFlag, int min, int max) {
this.local = local;
flags = new HashSet<Character>();
List<String> argsList = new ArrayList<String>(tokens.length);
for (String token : tokens) {
if (token.isEmpty()) {
// Do nothing
} else if (token.charAt(0) == '-' && token.length() > 1
&& Character.isLetter(token.charAt(1))) {
for (char flag : token.substring(1).toCharArray()) {
if (!allowedFlag.contains(flag)) {
throw new CommandUsageError(String.format(local.invalidFlag(), flag));
}
flags.add(flag);
}
} else {
argsList.add(token);
}
}
if (argsList.size() < min) {
throw new CommandUsageError(String.format(local.missingArguments(),
argsList.size(), min));
}
if (max != -1 && argsList.size() > max) {
throw new CommandUsageError(String.format(local.tooManyArguments(),
argsList.size(), max));
}
args = argsList.toArray(new String[0]);
}
|
diff --git a/src/main/java/com/carlgo11/simpleautomessage/metrics/CustomGraphs.java b/src/main/java/com/carlgo11/simpleautomessage/metrics/CustomGraphs.java
index 96c81a5..71bf347 100644
--- a/src/main/java/com/carlgo11/simpleautomessage/metrics/CustomGraphs.java
+++ b/src/main/java/com/carlgo11/simpleautomessage/metrics/CustomGraphs.java
@@ -1,73 +1,73 @@
package com.carlgo11.simpleautomessage.metrics;
import com.carlgo11.simpleautomessage.Main;
public class CustomGraphs {
public static void graphs(Metrics metrics, Main Main)
{ // Custom Graphs. Sends data to mcstats.org
try {
//Graph1
- Metrics.Graph graph1 = metrics.createGraph("Messages"); //Sends data about how many msg strings the user has.
+ Metrics.Graph graph1 = metrics.createGraph("Messages"); //Sends data about how many msg strings the server has.
int o = 0;
for (int i = 1; Main.getConfig().contains("msg" + i); i++) {
o = i;
}
graph1.addPlotter(new SimplePlotter("" + o));
//graph2
Metrics.Graph graph2 = metrics.createGraph("auto-update"); //Sends auto-update data. if auto-update: is true it returns 'enabled'.
if (Main.getConfig().getBoolean("auto-update") == true) {
graph2.addPlotter(new SimplePlotter("enabled"));
} else {
graph2.addPlotter(new SimplePlotter("disabled"));
}
//Graph3
Metrics.Graph graph3 = metrics.createGraph("language");
if (Main.getConfig().getString("language").equalsIgnoreCase("EN") || Main.getConfig().getString("language").isEmpty()) {
graph3.addPlotter(new SimplePlotter("English"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("FR")) {
graph3.addPlotter(new SimplePlotter("French"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("NL")) {
graph3.addPlotter(new SimplePlotter("Dutch"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Swedish"));
}
if (!Main.getConfig().getString("language").equalsIgnoreCase("EN") && !Main.getConfig().getString("language").equalsIgnoreCase("FR") && !Main.getConfig().getString("language").equalsIgnoreCase("NL") && !Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Other"));
}
//Graph4
Metrics.Graph graph4 = metrics.createGraph("min-players");
graph4.addPlotter(new SimplePlotter("" + Main.getConfig().getInt("min-players")));
//Graph5
Metrics.Graph graph5 = metrics.createGraph("random");
if (Main.getConfig().getBoolean("random")) {
graph5.addPlotter(new SimplePlotter("enabled"));
} else {
graph5.addPlotter(new SimplePlotter("disabled"));
}
//Graph6
Metrics.Graph graph6 = metrics.createGraph("warn-update");
if (!Main.getConfig().getBoolean("auto-update")) {
if (Main.getConfig().getString("warn-update0").equalsIgnoreCase("op")) {
graph6.addPlotter(new SimplePlotter("op"));
} else if (Main.getConfig().getString("warn-update").equalsIgnoreCase("perm")) {
graph6.addPlotter(new SimplePlotter("perm"));
} else {
graph6.addPlotter(new SimplePlotter("none"));
}
}
Main.debug("Sending metrics data...");
metrics.start();
} catch (Exception e) {
Main.logger.warning(e.getMessage());
}
}
}
| true | true | public static void graphs(Metrics metrics, Main Main)
{ // Custom Graphs. Sends data to mcstats.org
try {
//Graph1
Metrics.Graph graph1 = metrics.createGraph("Messages"); //Sends data about how many msg strings the user has.
int o = 0;
for (int i = 1; Main.getConfig().contains("msg" + i); i++) {
o = i;
}
graph1.addPlotter(new SimplePlotter("" + o));
//graph2
Metrics.Graph graph2 = metrics.createGraph("auto-update"); //Sends auto-update data. if auto-update: is true it returns 'enabled'.
if (Main.getConfig().getBoolean("auto-update") == true) {
graph2.addPlotter(new SimplePlotter("enabled"));
} else {
graph2.addPlotter(new SimplePlotter("disabled"));
}
//Graph3
Metrics.Graph graph3 = metrics.createGraph("language");
if (Main.getConfig().getString("language").equalsIgnoreCase("EN") || Main.getConfig().getString("language").isEmpty()) {
graph3.addPlotter(new SimplePlotter("English"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("FR")) {
graph3.addPlotter(new SimplePlotter("French"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("NL")) {
graph3.addPlotter(new SimplePlotter("Dutch"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Swedish"));
}
if (!Main.getConfig().getString("language").equalsIgnoreCase("EN") && !Main.getConfig().getString("language").equalsIgnoreCase("FR") && !Main.getConfig().getString("language").equalsIgnoreCase("NL") && !Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Other"));
}
//Graph4
Metrics.Graph graph4 = metrics.createGraph("min-players");
graph4.addPlotter(new SimplePlotter("" + Main.getConfig().getInt("min-players")));
//Graph5
Metrics.Graph graph5 = metrics.createGraph("random");
if (Main.getConfig().getBoolean("random")) {
graph5.addPlotter(new SimplePlotter("enabled"));
} else {
graph5.addPlotter(new SimplePlotter("disabled"));
}
//Graph6
Metrics.Graph graph6 = metrics.createGraph("warn-update");
if (!Main.getConfig().getBoolean("auto-update")) {
if (Main.getConfig().getString("warn-update0").equalsIgnoreCase("op")) {
graph6.addPlotter(new SimplePlotter("op"));
} else if (Main.getConfig().getString("warn-update").equalsIgnoreCase("perm")) {
graph6.addPlotter(new SimplePlotter("perm"));
} else {
graph6.addPlotter(new SimplePlotter("none"));
}
}
Main.debug("Sending metrics data...");
metrics.start();
} catch (Exception e) {
Main.logger.warning(e.getMessage());
}
}
| public static void graphs(Metrics metrics, Main Main)
{ // Custom Graphs. Sends data to mcstats.org
try {
//Graph1
Metrics.Graph graph1 = metrics.createGraph("Messages"); //Sends data about how many msg strings the server has.
int o = 0;
for (int i = 1; Main.getConfig().contains("msg" + i); i++) {
o = i;
}
graph1.addPlotter(new SimplePlotter("" + o));
//graph2
Metrics.Graph graph2 = metrics.createGraph("auto-update"); //Sends auto-update data. if auto-update: is true it returns 'enabled'.
if (Main.getConfig().getBoolean("auto-update") == true) {
graph2.addPlotter(new SimplePlotter("enabled"));
} else {
graph2.addPlotter(new SimplePlotter("disabled"));
}
//Graph3
Metrics.Graph graph3 = metrics.createGraph("language");
if (Main.getConfig().getString("language").equalsIgnoreCase("EN") || Main.getConfig().getString("language").isEmpty()) {
graph3.addPlotter(new SimplePlotter("English"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("FR")) {
graph3.addPlotter(new SimplePlotter("French"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("NL")) {
graph3.addPlotter(new SimplePlotter("Dutch"));
}
if (Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Swedish"));
}
if (!Main.getConfig().getString("language").equalsIgnoreCase("EN") && !Main.getConfig().getString("language").equalsIgnoreCase("FR") && !Main.getConfig().getString("language").equalsIgnoreCase("NL") && !Main.getConfig().getString("language").equalsIgnoreCase("SE")) {
graph3.addPlotter(new SimplePlotter("Other"));
}
//Graph4
Metrics.Graph graph4 = metrics.createGraph("min-players");
graph4.addPlotter(new SimplePlotter("" + Main.getConfig().getInt("min-players")));
//Graph5
Metrics.Graph graph5 = metrics.createGraph("random");
if (Main.getConfig().getBoolean("random")) {
graph5.addPlotter(new SimplePlotter("enabled"));
} else {
graph5.addPlotter(new SimplePlotter("disabled"));
}
//Graph6
Metrics.Graph graph6 = metrics.createGraph("warn-update");
if (!Main.getConfig().getBoolean("auto-update")) {
if (Main.getConfig().getString("warn-update0").equalsIgnoreCase("op")) {
graph6.addPlotter(new SimplePlotter("op"));
} else if (Main.getConfig().getString("warn-update").equalsIgnoreCase("perm")) {
graph6.addPlotter(new SimplePlotter("perm"));
} else {
graph6.addPlotter(new SimplePlotter("none"));
}
}
Main.debug("Sending metrics data...");
metrics.start();
} catch (Exception e) {
Main.logger.warning(e.getMessage());
}
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index df5b8b6..1f60740 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,669 +1,669 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.server.Server;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.map.fastfindgrid.Traceable;
import java.util.List;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Polygon;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private Traceable caster3;
private SimplePosition target;
/**
* Mittelpunkt für arc-Bewegungen
*/
private SimplePosition around;
/**
* Aktuelle Bewegung eine Kurve?
*/
private boolean arc;
/**
* Richtung der Kurve (true = Plus)
*/
private boolean arcDirection;
/**
* Wie weit (im Bogenmaß) wir auf dem Kreis laufen müssen
*/
private double tethaDist;
/**
* Wie weit wir (im Bogenmaß) auf dem Kreis schon gelaufen sind
*/
private double movedTetha;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
private GroupMember pathManager;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im Weg steht und man wartet bis es den Weg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 3000000000l;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
/**
* Ein simples Flag, das nach dem Kollisionstest gesetzt ist.
*/
private boolean colliding = false;
/**
* Zeigt nach dem Kollisionstest auf das letzte (kollidierende) Objekt.
*/
private Moveable lastObstacle;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, Traceable caster3, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.caster3 = caster3;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
movedTetha += Math.abs(newTetha - tetha);
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
newTetha = -2 * Math.PI + newTetha;
} else if (newTetha < -Math.PI) {
newTetha = 2 * Math.PI + newTetha;
}
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle, target);
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
boolean arcDone = false;
if (arc) {
arcDone = movedTetha >= tethaDist;
}
if (((!arc && vec.isOpposite(nextVec)) || arcDone || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
private void setMoveable(FloatingPointPosition from, FloatingPointPosition to) {
caster2.setMainPosition(to);
// Neuer Sektor?
while (pathManager.nextSectorBorder() != null && pathManager.nextSectorBorder().sidesDiffer(from, to)) {
// Ja, alten löschen und neuen setzen!
SectorChangingEdge edge = pathManager.borderCrossed();
caster2.setMyPoly(edge.getNext(caster2.getMyPoly()));
}
// Schnellsuchraster aktualisieren:
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* Falls arc true ist, werden arcDirection und arcCenter ausgewertet, sonst nicht.
* @param pos die Zielposition
* @param arc ob das Ziel auf einer Kurve angesteuert werden soll (true)
* @param arcDirection Richtung der Kurve (true - Bogenmaß-Plusrichtung)
* @param arcCenter um welchen Punkt gedreht werden soll.
*/
public synchronized void setTargetVector(SimplePosition pos, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null (" + arc + ")");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position (" + arc + ")");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
this.arc = arc;
this.arcDirection = arcDirection;
this.around = arcCenter;
this.movedTetha = 0;
if (arc) {
// Länge des Kreissegments berechnen
double startTetha = Math.atan2(caster2.getPrecisePosition().y() - around.y(), caster2.getPrecisePosition().x() - around.x());
double targetTetha = Math.atan2(target.y() - around.y(), target.x() - around.x());
if (arcDirection) {
tethaDist = targetTetha - startTetha;
} else {
tethaDist = startTetha - targetTetha;
}
if (tethaDist < 0) {
tethaDist = 2 * Math.PI + tethaDist;
}
}
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
changeSpeed(speed);
setTargetVector(pos, arc, arcDirection, arcCenter);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Untersucht die gegebene Route auf Echtzeitkollision.
* Sollte alles frei sein, wird to zurückgegeben.
* Ansonsten gibts eine neue Position, bis zu der problemlos gelaufen werden kann.
* Im schlimmsten Fall ist dies die from-Position, die frei sein MUSS!
* @param from von wo wir uns losbewegen
* @param to wohin wir laufen
* @return FloatingPointPosition bis wohin man laufen kann.
*/
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf den Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
// Zuerst Mittelpunkt der Linie durch beide Schnittpunkte berechnen:
Vector direct = new Vector(around.x() - obst.x(), around.y() - obst.y());
double moveRad = from.toFPP().getDistance(around.toFPP());
Vector z1 = direct.normalize().multiply(caster2.getRadius() + radius);
Vector z2 = direct.normalize().multiply(direct.length() - moveRad);
Vector mid = direct.normalize().multiply((z1.length() + z2.length()) / 2.0);
// Senkrechten Vektor und seine Länge berechnen:
Vector ortho2 = new Vector(direct.y(), -direct.x());
ortho2 = ortho2.normalize().multiply(Math.sqrt(((caster2.getRadius() + radius) * (caster2.getRadius() + radius)) - (mid.length() * mid.length())));
// Schnittpunkte ausrechnen:
Vector posMid = new Vector(obst.x() + mid.x(), obst.y() + mid.y()); // Positionsvektor des Mittelpunkts
Vector s1 = posMid.add(ortho2);
Vector s2 = posMid.add(ortho2.getInverted());
// Ausbrüten, ob s1 oder s2 der richtige ist:
Vector newPosVec = null;
double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(around.y() - s1.y(), around.x() - s1.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(around.y() - s2.y(), around.x() - s2.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
- to = around.toVector().add(newPosVec).toFPP();
+ to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
/**
* Hiermit lässt sich herausfinden, ob dieser mover gerade wartet, weil jemand im Weg steht.
* @return
*/
boolean isWaiting() {
return wait;
}
/**
* @return the pathManager
*/
GroupMember getPathManager() {
return pathManager;
}
/**
* @param pathManager the pathManager to set
*/
void setPathManager(GroupMember pathManager) {
this.pathManager = pathManager;
}
/**
* Findet heraus, ob das gegebenen Moveable auf dem gegebenen zu laufenden Abschnitt liegt,
* also eine Kollision darstellt.
* @param t
* @return true, wenn Kollision
*/
private boolean collidesOnArc(Moveable t, SimplePosition around, double colRadius, SimplePosition from, SimplePosition to) {
if (!arc) {
return false;
}
// Muss in +arc-Richtung erfolgen, notfalls start und Ziel tauschen
if (!arcDirection) {
SimplePosition back = from;
from = to;
to = back;
}
// Zuerst auf Nähe des gesamten Kreissegments testen
double dist = t.getPrecisePosition().getDistance(around.toFPP());
double moveRad = from.toFPP().getDistance(around.toFPP());
double minCol = moveRad - colRadius - t.getRadius();
double maxCol = moveRad + colRadius + t.getRadius();
if (dist >= minCol && dist <= maxCol) {
// Mögliche Kollision!
// Winkeltest
double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double toTetha = Math.atan2(around.y() - to.y(), around.x() - to.x());
if (toTetha < 0) {
toTetha += 2 * Math.PI;
}
double colTetha = Math.atan2(around.y() - t.getPrecisePosition().y(), around.x() - t.getPrecisePosition().x());
if (colTetha < 0) {
colTetha += 2 * Math.PI;
}
// Zusätzlichen Umlauf beachten
if (toTetha < fromTetha) {
if (colTetha < toTetha) {
colTetha += 2 * Math.PI;
}
toTetha += 2 * Math.PI;
}
if (colTetha >= fromTetha && colTetha <= toTetha) {
// Dann auf jeden Fall
return true;
}
// Sonst weitertesten: Der 6-Punkte-Test
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), (float) t.getRadius());
Vector fromOrtho = new Vector(from.x() - around.x(), from.y() - around.y());
fromOrtho = fromOrtho.normalize().multiply(colRadius);
Vector toOrtho = new Vector(to.x() - around.x(), to.y() - around.y());
toOrtho = toOrtho.normalize().multiply(colRadius);
SimplePosition t1 = from.toVector().add(fromOrtho);
SimplePosition t2 = from.toVector();
SimplePosition t3 = from.toVector().add(fromOrtho.getInverted());
SimplePosition t4 = to.toVector().add(toOrtho);
SimplePosition t5 = to.toVector();
SimplePosition t6 = to.toVector().add(toOrtho.normalize());
if (c.contains((float) t1.x(), (float) t1.y())
|| c.contains((float) t2.x(), (float) t2.y())
|| c.contains((float) t3.x(), (float) t3.y())
|| c.contains((float) t4.x(), (float) t4.y())
|| c.contains((float) t5.x(), (float) t5.y())
|| c.contains((float) t6.x(), (float) t6.y())) {
return true;
}
}
return false;
}
}
| true | true | private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf den Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
// Zuerst Mittelpunkt der Linie durch beide Schnittpunkte berechnen:
Vector direct = new Vector(around.x() - obst.x(), around.y() - obst.y());
double moveRad = from.toFPP().getDistance(around.toFPP());
Vector z1 = direct.normalize().multiply(caster2.getRadius() + radius);
Vector z2 = direct.normalize().multiply(direct.length() - moveRad);
Vector mid = direct.normalize().multiply((z1.length() + z2.length()) / 2.0);
// Senkrechten Vektor und seine Länge berechnen:
Vector ortho2 = new Vector(direct.y(), -direct.x());
ortho2 = ortho2.normalize().multiply(Math.sqrt(((caster2.getRadius() + radius) * (caster2.getRadius() + radius)) - (mid.length() * mid.length())));
// Schnittpunkte ausrechnen:
Vector posMid = new Vector(obst.x() + mid.x(), obst.y() + mid.y()); // Positionsvektor des Mittelpunkts
Vector s1 = posMid.add(ortho2);
Vector s2 = posMid.add(ortho2.getInverted());
// Ausbrüten, ob s1 oder s2 der richtige ist:
Vector newPosVec = null;
double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(around.y() - s1.y(), around.x() - s1.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(around.y() - s2.y(), around.x() - s2.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
to = around.toVector().add(newPosVec).toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
| private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf den Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
// Zuerst Mittelpunkt der Linie durch beide Schnittpunkte berechnen:
Vector direct = new Vector(around.x() - obst.x(), around.y() - obst.y());
double moveRad = from.toFPP().getDistance(around.toFPP());
Vector z1 = direct.normalize().multiply(caster2.getRadius() + radius);
Vector z2 = direct.normalize().multiply(direct.length() - moveRad);
Vector mid = direct.normalize().multiply((z1.length() + z2.length()) / 2.0);
// Senkrechten Vektor und seine Länge berechnen:
Vector ortho2 = new Vector(direct.y(), -direct.x());
ortho2 = ortho2.normalize().multiply(Math.sqrt(((caster2.getRadius() + radius) * (caster2.getRadius() + radius)) - (mid.length() * mid.length())));
// Schnittpunkte ausrechnen:
Vector posMid = new Vector(obst.x() + mid.x(), obst.y() + mid.y()); // Positionsvektor des Mittelpunkts
Vector s1 = posMid.add(ortho2);
Vector s2 = posMid.add(ortho2.getInverted());
// Ausbrüten, ob s1 oder s2 der richtige ist:
Vector newPosVec = null;
double fromTetha = Math.atan2(around.y() - from.y(), around.x() - from.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(around.y() - s1.y(), around.x() - s1.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(around.y() - s2.y(), around.x() - s2.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
|
diff --git a/source/src/net/grinder/engine/agent/Agent.java b/source/src/net/grinder/engine/agent/Agent.java
index 6362dd40..949e6422 100755
--- a/source/src/net/grinder/engine/agent/Agent.java
+++ b/source/src/net/grinder/engine/agent/Agent.java
@@ -1,464 +1,463 @@
// Copyright (C) 2000 Paco Gomez
// Copyright (C) 2000-2007 Philip Aston
// Copyright (C) 2004 Bertrand Ave
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
package net.grinder.engine.agent;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import net.grinder.common.GrinderBuild;
import net.grinder.common.GrinderException;
import net.grinder.common.GrinderProperties;
import net.grinder.common.Logger;
import net.grinder.communication.ClientReceiver;
import net.grinder.communication.ClientSender;
import net.grinder.communication.CommunicationDefaults;
import net.grinder.communication.CommunicationException;
import net.grinder.communication.ConnectionType;
import net.grinder.communication.Connector;
import net.grinder.communication.FanOutStreamSender;
import net.grinder.communication.MessageDispatchSender;
import net.grinder.communication.MessagePump;
import net.grinder.communication.TeeSender;
import net.grinder.console.messages.AgentProcessReportMessage;
import net.grinder.engine.common.ConsoleListener;
import net.grinder.engine.common.EngineException;
import net.grinder.engine.common.ScriptLocation;
import net.grinder.engine.messages.StartGrinderMessage;
import net.grinder.util.Directory;
import net.grinder.util.JVM;
import net.grinder.util.Directory.DirectoryException;
import net.grinder.util.thread.Monitor;
/**
* This is the entry point of The Grinder agent process.
*
* @author Paco Gomez
* @author Philip Aston
* @author Bertrand Ave
* @version $Revision$
*/
public final class Agent {
private final File m_alternateFile;
private final Logger m_logger;
private final Timer m_timer;
private final Monitor m_eventSynchronisation = new Monitor();
private final AgentIdentityImplementation m_agentIdentity;
private final ConsoleListener m_consoleListener;
private final FanOutStreamSender m_fanOutStreamSender =
new FanOutStreamSender(3);
/**
* We use an most one file store throughout an agent's life, but can't
* initialise it until we've read the properties and connected to the console.
*/
private FileStore m_fileStore;
/**
* Constructor.
*
* @param logger Logger.
* @param alternateFile Alternative properties file, or <code>null</code>.
* @throws GrinderException If an error occurs.
*/
public Agent(Logger logger, File alternateFile) throws GrinderException {
m_alternateFile = alternateFile;
m_timer = new Timer(true);
m_logger = logger;
m_consoleListener = new ConsoleListener(m_eventSynchronisation, m_logger);
m_agentIdentity = new AgentIdentityImplementation(getHostName());
if (!JVM.getInstance().haveRequisites(m_logger)) {
return;
}
}
/**
* Run the Grinder agent process.
*
* @throws GrinderException If an error occurs.
*/
public void run() throws GrinderException {
ConsoleCommunication consoleCommunication = null;
StartGrinderMessage startMessage = null;
while (true) {
m_logger.output(GrinderBuild.getName());
ScriptLocation script = null;
GrinderProperties properties = null;
do {
properties = new GrinderProperties(m_alternateFile);
if (startMessage != null) {
properties.putAll(startMessage.getProperties());
}
m_agentIdentity.setName(
properties.getProperty("grinder.hostID", getHostName()));
final Connector connector;
if (properties.getBoolean("grinder.useConsole", true)) {
connector = new Connector(
properties.getProperty("grinder.consoleHost",
CommunicationDefaults.CONSOLE_HOST),
properties.getInt("grinder.consolePort",
CommunicationDefaults.CONSOLE_PORT),
ConnectionType.AGENT);
}
else {
connector = null;
}
// We only reconnect if the connection details have changed.
if (consoleCommunication != null &&
!consoleCommunication.getConnector().equals(connector)) {
consoleCommunication.shutdown();
m_consoleListener.discardMessages(ConsoleListener.ANY);
consoleCommunication = null;
startMessage = null;
}
if (consoleCommunication == null && connector != null) {
try {
consoleCommunication = new ConsoleCommunication(connector);
}
catch (CommunicationException e) {
m_logger.error(
e.getMessage() + ", proceeding without the console; set " +
"grinder.useConsole=false to disable this warning.");
}
}
if (consoleCommunication != null && startMessage == null) {
m_logger.output("waiting for console signal");
m_consoleListener.waitForMessage();
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
continue; // Loop to handle new properties.
}
else {
// Some other message, we check what this at the end of the
// outer while loop.
break;
}
}
if (startMessage != null) {
// If the start message doesn't specify a script in the cache,
// we'll fall back to the agent properties, and then to "grinder.py".
final File scriptFromConsole =
startMessage.getProperties().getFile("grinder.script", null);
if (scriptFromConsole != null) {
// The script directory may not be the file's direct parent.
- script = new ScriptLocation(
- m_fileStore.getDirectory(),
- m_fileStore.getDirectory().getFile(scriptFromConsole.getPath()));
+ script =
+ new ScriptLocation(m_fileStore.getDirectory(), scriptFromConsole);
}
}
if (script == null) {
final File scriptFile =
new File(properties.getProperty("grinder.script", "grinder.py"));
try {
script = new ScriptLocation(
new Directory(scriptFile.getAbsoluteFile().getParentFile()),
scriptFile);
}
catch (DirectoryException e) {
m_logger.error("The script '" + scriptFile + "' does not exist.");
break;
}
}
if (!script.getFile().canRead()) {
m_logger.error("The script file '" + script +
"' does not exist or is not readable.");
script = null;
break;
}
}
while (script == null);
if (script != null) {
final boolean singleProcess =
properties.getBoolean("grinder.debug.singleprocess", false);
final String jvmArguments =
properties.getProperty("grinder.jvm.arguments");
final WorkerFactory workerFactory;
if (!singleProcess) {
final WorkerProcessCommandLine workerCommandLine =
new WorkerProcessCommandLine(properties,
System.getProperties(),
jvmArguments);
m_logger.output("Worker process command line: " + workerCommandLine);
workerFactory =
new ProcessWorkerFactory(
workerCommandLine, m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
else {
m_logger.output("DEBUG MODE: Spawning threads rather than processes");
if (jvmArguments != null) {
m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments +
") ignored in single process mode");
}
workerFactory =
new DebugThreadWorkerFactory(
m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
final WorkerLauncher workerLauncher =
new WorkerLauncher(properties.getInt("grinder.processes", 1),
workerFactory, m_eventSynchronisation, m_logger);
final int processIncrement =
properties.getInt("grinder.processIncrement", 0);
if (processIncrement > 0) {
final boolean moreProcessesToStart =
workerLauncher.startSomeWorkers(
properties.getInt("grinder.initialProcesses", processIncrement));
if (moreProcessesToStart) {
final int incrementInterval =
properties.getInt("grinder.processIncrementInterval", 60000);
final RampUpTimerTask rampUpTimerTask =
new RampUpTimerTask(workerLauncher, processIncrement);
m_timer.scheduleAtFixedRate(
rampUpTimerTask, incrementInterval, incrementInterval);
}
}
else {
workerLauncher.startAllWorkers();
}
// Wait for a termination event.
synchronized (m_eventSynchronisation) {
final long maximumShutdownTime = 20000;
long consoleSignalTime = -1;
while (!workerLauncher.allFinished()) {
if (consoleSignalTime == -1 &&
m_consoleListener.checkForMessage(ConsoleListener.ANY ^
ConsoleListener.START)) {
workerLauncher.dontStartAnyMore();
consoleSignalTime = System.currentTimeMillis();
}
if (consoleSignalTime >= 0 &&
System.currentTimeMillis() - consoleSignalTime >
maximumShutdownTime) {
m_logger.output("forcibly terminating unresponsive processes");
workerLauncher.destroyAllWorkers();
}
m_eventSynchronisation.waitNoInterrruptException(
maximumShutdownTime);
}
}
workerLauncher.shutdown();
}
if (consoleCommunication == null) {
break;
}
else {
// Ignore any pending start messages.
m_consoleListener.discardMessages(ConsoleListener.START);
if (!m_consoleListener.received(ConsoleListener.ANY)) {
// We've got here naturally, without a console signal.
m_logger.output("finished, waiting for console signal");
m_consoleListener.waitForMessage();
}
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
}
else if (m_consoleListener.received(ConsoleListener.STOP |
ConsoleListener.SHUTDOWN)) {
break;
}
else {
// ConsoleListener.RESET or natural death.
startMessage = null;
}
}
}
}
/**
* Clean up resources.
*/
public void shutdown() {
m_timer.cancel();
m_fanOutStreamSender.shutdown();
m_logger.output("finished");
}
private static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e) {
return "UNNAMED HOST";
}
}
private static class RampUpTimerTask extends TimerTask {
private final WorkerLauncher m_processLauncher;
private final int m_processIncrement;
public RampUpTimerTask(WorkerLauncher processLauncher,
int processIncrement) {
m_processLauncher = processLauncher;
m_processIncrement = processIncrement;
}
public void run() {
try {
final boolean moreProcessesToStart =
m_processLauncher.startSomeWorkers(m_processIncrement);
if (!moreProcessesToStart) {
super.cancel();
}
}
catch (EngineException e) {
// Really an assertion. Can't use logger because its not thread-safe.
System.err.println("Failed to start processes");
e.printStackTrace();
}
}
}
private final class ConsoleCommunication {
private final ClientReceiver m_receiver;
private final ClientSender m_sender;
private final Connector m_connector;
private final TimerTask m_reportRunningTask;
public ConsoleCommunication(Connector connector)
throws CommunicationException, FileStore.FileStoreException {
m_receiver = ClientReceiver.connect(connector);
m_sender = ClientSender.connect(m_receiver);
m_connector = connector;
m_sender.send(
new AgentProcessReportMessage(
m_agentIdentity,
AgentProcessReportMessage.STATE_STARTED));
if (m_fileStore == null) {
// Only create the file store if we connected.
m_fileStore =
new FileStore(
new File("./" + m_agentIdentity.getName() + "-file-store"),
m_logger);
}
final MessageDispatchSender fileStoreMessageDispatcher =
new MessageDispatchSender();
m_fileStore.registerMessageHandlers(fileStoreMessageDispatcher);
final MessageDispatchSender messageDispatcher =
new MessageDispatchSender();
m_consoleListener.registerMessageHandlers(messageDispatcher);
// Everything that the file store doesn't handle is tee'd to the
// worker processes and our message handlers.
fileStoreMessageDispatcher.addFallback(
new TeeSender(messageDispatcher, m_fanOutStreamSender));
new MessagePump(m_receiver, fileStoreMessageDispatcher, 1);
m_reportRunningTask = new TimerTask() {
public void run() {
try {
m_sender.send(
new AgentProcessReportMessage(
m_agentIdentity,
AgentProcessReportMessage.STATE_RUNNING));
}
catch (CommunicationException e) {
cancel();
}
}
};
m_timer.schedule(m_reportRunningTask, 1000, 1000);
}
public Connector getConnector() {
return m_connector;
}
public void shutdown() {
m_reportRunningTask.cancel();
try {
m_sender.send(
new AgentProcessReportMessage(
m_agentIdentity,
AgentProcessReportMessage.STATE_FINISHED));
}
catch (CommunicationException e) {
// Ignore - peer has probably shut down.
}
finally {
m_receiver.shutdown();
m_sender.shutdown();
}
}
}
}
| true | true | public void run() throws GrinderException {
ConsoleCommunication consoleCommunication = null;
StartGrinderMessage startMessage = null;
while (true) {
m_logger.output(GrinderBuild.getName());
ScriptLocation script = null;
GrinderProperties properties = null;
do {
properties = new GrinderProperties(m_alternateFile);
if (startMessage != null) {
properties.putAll(startMessage.getProperties());
}
m_agentIdentity.setName(
properties.getProperty("grinder.hostID", getHostName()));
final Connector connector;
if (properties.getBoolean("grinder.useConsole", true)) {
connector = new Connector(
properties.getProperty("grinder.consoleHost",
CommunicationDefaults.CONSOLE_HOST),
properties.getInt("grinder.consolePort",
CommunicationDefaults.CONSOLE_PORT),
ConnectionType.AGENT);
}
else {
connector = null;
}
// We only reconnect if the connection details have changed.
if (consoleCommunication != null &&
!consoleCommunication.getConnector().equals(connector)) {
consoleCommunication.shutdown();
m_consoleListener.discardMessages(ConsoleListener.ANY);
consoleCommunication = null;
startMessage = null;
}
if (consoleCommunication == null && connector != null) {
try {
consoleCommunication = new ConsoleCommunication(connector);
}
catch (CommunicationException e) {
m_logger.error(
e.getMessage() + ", proceeding without the console; set " +
"grinder.useConsole=false to disable this warning.");
}
}
if (consoleCommunication != null && startMessage == null) {
m_logger.output("waiting for console signal");
m_consoleListener.waitForMessage();
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
continue; // Loop to handle new properties.
}
else {
// Some other message, we check what this at the end of the
// outer while loop.
break;
}
}
if (startMessage != null) {
// If the start message doesn't specify a script in the cache,
// we'll fall back to the agent properties, and then to "grinder.py".
final File scriptFromConsole =
startMessage.getProperties().getFile("grinder.script", null);
if (scriptFromConsole != null) {
// The script directory may not be the file's direct parent.
script = new ScriptLocation(
m_fileStore.getDirectory(),
m_fileStore.getDirectory().getFile(scriptFromConsole.getPath()));
}
}
if (script == null) {
final File scriptFile =
new File(properties.getProperty("grinder.script", "grinder.py"));
try {
script = new ScriptLocation(
new Directory(scriptFile.getAbsoluteFile().getParentFile()),
scriptFile);
}
catch (DirectoryException e) {
m_logger.error("The script '" + scriptFile + "' does not exist.");
break;
}
}
if (!script.getFile().canRead()) {
m_logger.error("The script file '" + script +
"' does not exist or is not readable.");
script = null;
break;
}
}
while (script == null);
if (script != null) {
final boolean singleProcess =
properties.getBoolean("grinder.debug.singleprocess", false);
final String jvmArguments =
properties.getProperty("grinder.jvm.arguments");
final WorkerFactory workerFactory;
if (!singleProcess) {
final WorkerProcessCommandLine workerCommandLine =
new WorkerProcessCommandLine(properties,
System.getProperties(),
jvmArguments);
m_logger.output("Worker process command line: " + workerCommandLine);
workerFactory =
new ProcessWorkerFactory(
workerCommandLine, m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
else {
m_logger.output("DEBUG MODE: Spawning threads rather than processes");
if (jvmArguments != null) {
m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments +
") ignored in single process mode");
}
workerFactory =
new DebugThreadWorkerFactory(
m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
final WorkerLauncher workerLauncher =
new WorkerLauncher(properties.getInt("grinder.processes", 1),
workerFactory, m_eventSynchronisation, m_logger);
final int processIncrement =
properties.getInt("grinder.processIncrement", 0);
if (processIncrement > 0) {
final boolean moreProcessesToStart =
workerLauncher.startSomeWorkers(
properties.getInt("grinder.initialProcesses", processIncrement));
if (moreProcessesToStart) {
final int incrementInterval =
properties.getInt("grinder.processIncrementInterval", 60000);
final RampUpTimerTask rampUpTimerTask =
new RampUpTimerTask(workerLauncher, processIncrement);
m_timer.scheduleAtFixedRate(
rampUpTimerTask, incrementInterval, incrementInterval);
}
}
else {
workerLauncher.startAllWorkers();
}
// Wait for a termination event.
synchronized (m_eventSynchronisation) {
final long maximumShutdownTime = 20000;
long consoleSignalTime = -1;
while (!workerLauncher.allFinished()) {
if (consoleSignalTime == -1 &&
m_consoleListener.checkForMessage(ConsoleListener.ANY ^
ConsoleListener.START)) {
workerLauncher.dontStartAnyMore();
consoleSignalTime = System.currentTimeMillis();
}
if (consoleSignalTime >= 0 &&
System.currentTimeMillis() - consoleSignalTime >
maximumShutdownTime) {
m_logger.output("forcibly terminating unresponsive processes");
workerLauncher.destroyAllWorkers();
}
m_eventSynchronisation.waitNoInterrruptException(
maximumShutdownTime);
}
}
workerLauncher.shutdown();
}
if (consoleCommunication == null) {
break;
}
else {
// Ignore any pending start messages.
m_consoleListener.discardMessages(ConsoleListener.START);
if (!m_consoleListener.received(ConsoleListener.ANY)) {
// We've got here naturally, without a console signal.
m_logger.output("finished, waiting for console signal");
m_consoleListener.waitForMessage();
}
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
}
else if (m_consoleListener.received(ConsoleListener.STOP |
ConsoleListener.SHUTDOWN)) {
break;
}
else {
// ConsoleListener.RESET or natural death.
startMessage = null;
}
}
}
}
| public void run() throws GrinderException {
ConsoleCommunication consoleCommunication = null;
StartGrinderMessage startMessage = null;
while (true) {
m_logger.output(GrinderBuild.getName());
ScriptLocation script = null;
GrinderProperties properties = null;
do {
properties = new GrinderProperties(m_alternateFile);
if (startMessage != null) {
properties.putAll(startMessage.getProperties());
}
m_agentIdentity.setName(
properties.getProperty("grinder.hostID", getHostName()));
final Connector connector;
if (properties.getBoolean("grinder.useConsole", true)) {
connector = new Connector(
properties.getProperty("grinder.consoleHost",
CommunicationDefaults.CONSOLE_HOST),
properties.getInt("grinder.consolePort",
CommunicationDefaults.CONSOLE_PORT),
ConnectionType.AGENT);
}
else {
connector = null;
}
// We only reconnect if the connection details have changed.
if (consoleCommunication != null &&
!consoleCommunication.getConnector().equals(connector)) {
consoleCommunication.shutdown();
m_consoleListener.discardMessages(ConsoleListener.ANY);
consoleCommunication = null;
startMessage = null;
}
if (consoleCommunication == null && connector != null) {
try {
consoleCommunication = new ConsoleCommunication(connector);
}
catch (CommunicationException e) {
m_logger.error(
e.getMessage() + ", proceeding without the console; set " +
"grinder.useConsole=false to disable this warning.");
}
}
if (consoleCommunication != null && startMessage == null) {
m_logger.output("waiting for console signal");
m_consoleListener.waitForMessage();
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
continue; // Loop to handle new properties.
}
else {
// Some other message, we check what this at the end of the
// outer while loop.
break;
}
}
if (startMessage != null) {
// If the start message doesn't specify a script in the cache,
// we'll fall back to the agent properties, and then to "grinder.py".
final File scriptFromConsole =
startMessage.getProperties().getFile("grinder.script", null);
if (scriptFromConsole != null) {
// The script directory may not be the file's direct parent.
script =
new ScriptLocation(m_fileStore.getDirectory(), scriptFromConsole);
}
}
if (script == null) {
final File scriptFile =
new File(properties.getProperty("grinder.script", "grinder.py"));
try {
script = new ScriptLocation(
new Directory(scriptFile.getAbsoluteFile().getParentFile()),
scriptFile);
}
catch (DirectoryException e) {
m_logger.error("The script '" + scriptFile + "' does not exist.");
break;
}
}
if (!script.getFile().canRead()) {
m_logger.error("The script file '" + script +
"' does not exist or is not readable.");
script = null;
break;
}
}
while (script == null);
if (script != null) {
final boolean singleProcess =
properties.getBoolean("grinder.debug.singleprocess", false);
final String jvmArguments =
properties.getProperty("grinder.jvm.arguments");
final WorkerFactory workerFactory;
if (!singleProcess) {
final WorkerProcessCommandLine workerCommandLine =
new WorkerProcessCommandLine(properties,
System.getProperties(),
jvmArguments);
m_logger.output("Worker process command line: " + workerCommandLine);
workerFactory =
new ProcessWorkerFactory(
workerCommandLine, m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
else {
m_logger.output("DEBUG MODE: Spawning threads rather than processes");
if (jvmArguments != null) {
m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments +
") ignored in single process mode");
}
workerFactory =
new DebugThreadWorkerFactory(
m_agentIdentity, m_fanOutStreamSender,
consoleCommunication != null, script, properties);
}
final WorkerLauncher workerLauncher =
new WorkerLauncher(properties.getInt("grinder.processes", 1),
workerFactory, m_eventSynchronisation, m_logger);
final int processIncrement =
properties.getInt("grinder.processIncrement", 0);
if (processIncrement > 0) {
final boolean moreProcessesToStart =
workerLauncher.startSomeWorkers(
properties.getInt("grinder.initialProcesses", processIncrement));
if (moreProcessesToStart) {
final int incrementInterval =
properties.getInt("grinder.processIncrementInterval", 60000);
final RampUpTimerTask rampUpTimerTask =
new RampUpTimerTask(workerLauncher, processIncrement);
m_timer.scheduleAtFixedRate(
rampUpTimerTask, incrementInterval, incrementInterval);
}
}
else {
workerLauncher.startAllWorkers();
}
// Wait for a termination event.
synchronized (m_eventSynchronisation) {
final long maximumShutdownTime = 20000;
long consoleSignalTime = -1;
while (!workerLauncher.allFinished()) {
if (consoleSignalTime == -1 &&
m_consoleListener.checkForMessage(ConsoleListener.ANY ^
ConsoleListener.START)) {
workerLauncher.dontStartAnyMore();
consoleSignalTime = System.currentTimeMillis();
}
if (consoleSignalTime >= 0 &&
System.currentTimeMillis() - consoleSignalTime >
maximumShutdownTime) {
m_logger.output("forcibly terminating unresponsive processes");
workerLauncher.destroyAllWorkers();
}
m_eventSynchronisation.waitNoInterrruptException(
maximumShutdownTime);
}
}
workerLauncher.shutdown();
}
if (consoleCommunication == null) {
break;
}
else {
// Ignore any pending start messages.
m_consoleListener.discardMessages(ConsoleListener.START);
if (!m_consoleListener.received(ConsoleListener.ANY)) {
// We've got here naturally, without a console signal.
m_logger.output("finished, waiting for console signal");
m_consoleListener.waitForMessage();
}
if (m_consoleListener.received(ConsoleListener.START)) {
startMessage = m_consoleListener.getLastStartGrinderMessage();
}
else if (m_consoleListener.received(ConsoleListener.STOP |
ConsoleListener.SHUTDOWN)) {
break;
}
else {
// ConsoleListener.RESET or natural death.
startMessage = null;
}
}
}
}
|
diff --git a/src/haven/error/HtmlReporter.java b/src/haven/error/HtmlReporter.java
index 163860a..3febedb 100644
--- a/src/haven/error/HtmlReporter.java
+++ b/src/haven/error/HtmlReporter.java
@@ -1,340 +1,340 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven.error;
import java.io.*;
import java.util.*;
import java.text.*;
public class HtmlReporter {
public static final DateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final NumberFormat ifmt = NumberFormat.getInstance();
public static final String[] idxprops = {
"java.vendor", "java.version",
"os.arch", "os.name", "os.version",
"thnm", "usr",
};
public static final Class[] boring = {
RuntimeException.class,
javax.media.opengl.GLException.class,
};
public static final Comparator<Throwable> thcmp = new Comparator<Throwable>() {
public int compare(Throwable a, Throwable b) {
int sc = a.getClass().getName().compareTo(b.getClass().getName());
if(sc != 0)
return(sc);
StackTraceElement[] at = a.getStackTrace(), bt = b.getStackTrace();
if(at.length != bt.length)
return(at.length - bt.length);
for(int i = 0; i < at.length; i++) {
sc = at[i].getFileName().compareTo(bt[i].getFileName());
if(sc != 0)
return(sc);
sc = at[i].getClassName().compareTo(bt[i].getClassName());
if(sc != 0)
return(sc);
sc = at[i].getMethodName().compareTo(bt[i].getMethodName());
if(sc != 0)
return(sc);
if(at[i].getLineNumber() != bt[i].getLineNumber())
return(at[i].getLineNumber() - bt[i].getLineNumber());
}
if((a.getCause() == null) && (b.getCause() == null))
return(0);
if(a.getCause() == null)
return(-1);
if(b.getCause() == null)
return(1);
return(compare(a.getCause(), b.getCause()));
}
};
public static class ErrorIdentity implements Comparable<ErrorIdentity> {
public String jarrev;
public Throwable t;
public ErrorIdentity(Report r) {
if((jarrev = (String)r.props.get("jar.git-rev")) == null)
jarrev = "";
t = r.t;
}
public int compareTo(ErrorIdentity o) {
int sc = jarrev.compareTo(o.jarrev);
if(sc != 0)
return(sc);
return(thcmp.compare(t, o.t));
}
public boolean equals(ErrorIdentity o) {
return(compareTo(o) == 0);
}
}
public static String htmlhead(String title) {
StringBuilder buf = new StringBuilder();
buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n");
buf.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-US\">\n");
buf.append("<head>\n");
buf.append("<title>" + title + "</title>\n");
buf.append("<link rel=\"stylesheet\" title=\"Haven error report\" type=\"text/css\" href=\"base.css\" />");
buf.append("</head>\n");
buf.append("<body>\n");
return(buf.toString());
}
public static String htmltail() {
StringBuilder buf = new StringBuilder();
buf.append("</body>\n");
buf.append("</html>\n");
return(buf.toString());
}
public static String htmlq(String html) {
if(html == null)
return("(null)");
StringBuilder buf = new StringBuilder();
for(int i = 0; i < html.length(); i++) {
char c = html.charAt(i);
if(c == '&')
buf.append("&");
else if(c == '<')
buf.append("<");
else if(c == '>')
buf.append(">");
else
buf.append(c);
}
return(buf.toString());
}
public static String htmlbt(StackTraceElement[] bt) {
StringBuilder buf = new StringBuilder();
buf.append("<table class=\"bt\">\n");
buf.append("<tr><th>Class</th><th>Function</th><th>File</th><th>Line</th></tr>\n");
for(StackTraceElement e : bt) {
List<String> classes = new LinkedList<String>();
String pkg = e.getClassName();
if(pkg != null) {
if(pkg.startsWith("javax.media.opengl.") || pkg.startsWith("com.sun.opengl.")) {
classes.add("pkg-jogl");
} else if(pkg.startsWith("java.") || pkg.startsWith("javax.")) {
classes.add("pkg-java");
} else if(pkg.startsWith("haven.") || pkg.startsWith("dolda.")) {
classes.add("own");
}
}
if(e.isNativeMethod())
classes.add("native");
buf.append("<tr");
if(classes.size() > 0) {
buf.append(" class=\"");
boolean f = true;
for(String cls : classes) {
if(!f)
buf.append(" ");
f = false;
buf.append(cls);
}
buf.append("\"");
}
buf.append(">");
buf.append("<td>" + htmlq(e.getClassName()) + "</td>");
buf.append("<td>" + htmlq(e.getMethodName()) + "</td>");
buf.append("<td>" + htmlq(e.getFileName()) + "</td>");
buf.append("<td>" + htmlq(Integer.toString(e.getLineNumber())) + "</td>");
buf.append("</tr>\n");
}
buf.append("<table>\n");
return(buf.toString());
}
public static void makereport(OutputStream outs, Report rep) throws IOException {
PrintWriter out = new PrintWriter(new OutputStreamWriter(outs, "UTF-8"));
out.print(htmlhead("Error Report"));
out.println("<h1>Error Report</h1>");
out.println("<p>Reported at: " + htmlq(dfmt.format(new Date(rep.time))) + "</p>");
out.println("<h2>Properties</h2>");
out.println("<table>");
out.println("<tr><th>Name</th><th>Value</th>");
SortedSet<String> keys = new TreeSet<String>(rep.props.keySet());
for(String key : keys) {
Object val = rep.props.get(key);
String vals;
if(val instanceof Number) {
vals = ifmt.format((Number)val);
} else if(val instanceof Date) {
vals = dfmt.format((Number)val);
} else {
vals = val.toString();
}
out.print(" <tr>");
out.print("<td>" + htmlq(key) + "</td><td>" + htmlq(vals) + "</td>");
out.println(" </tr>");
}
out.println("</table>");
out.println("<h2>Exception chain</h2>");
for(Throwable t = rep.t; t != null; t = t.getCause()) {
out.println("<h3>" + htmlq(t.getClass().getName()) + "</h3>");
out.println("<p>" + htmlq(t.getMessage()) + "</p>");
out.print(htmlbt(t.getStackTrace()));
}
out.print(htmltail());
out.flush();
}
public static Throwable findrootexc(Throwable t) {
if(t.getCause() == null)
return(t);
for(Class b : boring) {
if(t.getClass() == b)
return(findrootexc(t.getCause()));
}
return(t);
}
public static void makeindex(OutputStream outs, Map<File, Report> reports, Map<File, Exception> failed) throws IOException {
PrintWriter out = new PrintWriter(new OutputStreamWriter(outs, "UTF-8"));
out.print(htmlhead("Error Index"));
out.println("<h1>Error Index</h1>");
Set<String> props = new TreeSet<String>();
for(String pn : idxprops)
props.add(pn);
Map<ErrorIdentity, List<Map.Entry<File, Report>>> groups = new TreeMap<ErrorIdentity, List<Map.Entry<File, Report>>>();
for(Map.Entry<File, Report> rent : reports.entrySet()) {
ErrorIdentity id = new ErrorIdentity(rent.getValue());
- if(groups.get(id) != null)
+ if(groups.get(id) == null)
groups.put(id, new ArrayList<Map.Entry<File, Report>>());
groups.get(id).add(rent);
}
for(ErrorIdentity id : groups.keySet()) {
out.println("<h2>" + htmlq(findrootexc(id.t).getClass().getSimpleName()) + "</h2>");
out.println("<table><tr>");
out.println(" <th>File</th>");
out.println(" <th>Time</th>");
out.println(" <th>Exception</th>");
for(String pn : props)
out.println(" <th>" + htmlq(pn) + "</th>");
out.println("</tr>");
List<Map.Entry<File, Report>> reps = groups.get(id);
Collections.sort(reps, new Comparator<Map.Entry<File, Report>>() {
public int compare(Map.Entry<File, Report> a, Map.Entry<File, Report> b) {
long at = a.getValue().time, bt = b.getValue().time;
if(at > bt)
return(-1);
else if(at < bt)
return(1);
else
return(0);
}
});
for(Map.Entry<File, Report> rent : reps) {
File file = rent.getKey();
Report rep = rent.getValue();
out.println(" <tr>");
out.print(" <td>");
out.println("<a href=\"" + htmlq(file.getName()) + ".html\">");
out.print(htmlq(file.getName()));
out.println("</a></td>");
out.println(" <td>" + htmlq(dfmt.format(new Date(rep.time))) + "</td>");
out.println(" <td>" + htmlq(findrootexc(rep.t).getClass().getSimpleName()) + "</td>");
for(String pn : props) {
out.print(" <td>");
if(rep.props.containsKey(pn)) {
out.print(htmlq(rep.props.get(pn).toString()));
}
out.println("</td>");
}
out.println(" </tr>");
}
out.println("</table>");
}
if(failed.size() > 0) {
out.println("<h2>Unreadable reports</h2>");
out.println("<table>");
out.println("<tr><th>File</th><th>Exception</th>");
for(File file : failed.keySet()) {
Exception exc = failed.get(file);
out.print(" <tr>");
out.print("<td>" + htmlq(file.getName()) + "</td><td>" + htmlq(exc.getClass().getName()) + ": " + htmlq(exc.getMessage()) + "</td>");
out.println(" </tr>");
}
out.println("</table>");
}
out.print(htmltail());
out.flush();
}
public static void main(String[] args) throws Exception {
File indir = new File("/srv/haven/errors");
File outdir = new File("/srv/www/haven/errors");
Map<File, Report> reports = new HashMap<File, Report>();
Map<File, Exception> failed = new HashMap<File, Exception>();
for(File f : indir.listFiles()) {
if(f.getName().startsWith("err")) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
try {
reports.put(f, (Report)in.readObject());
} finally {
in.close();
}
} catch(Exception e) {
failed.put(f, e);
}
}
}
OutputStream out;
out = new FileOutputStream(new File(outdir, "index.html"));
try {
makeindex(out, reports, failed);
} finally {
out.close();
}
for(File f : reports.keySet()) {
out = new FileOutputStream(new File(outdir, f.getName() + ".html"));
try {
makereport(out, reports.get(f));
} finally {
out.close();
}
}
}
}
| true | true | public static void makeindex(OutputStream outs, Map<File, Report> reports, Map<File, Exception> failed) throws IOException {
PrintWriter out = new PrintWriter(new OutputStreamWriter(outs, "UTF-8"));
out.print(htmlhead("Error Index"));
out.println("<h1>Error Index</h1>");
Set<String> props = new TreeSet<String>();
for(String pn : idxprops)
props.add(pn);
Map<ErrorIdentity, List<Map.Entry<File, Report>>> groups = new TreeMap<ErrorIdentity, List<Map.Entry<File, Report>>>();
for(Map.Entry<File, Report> rent : reports.entrySet()) {
ErrorIdentity id = new ErrorIdentity(rent.getValue());
if(groups.get(id) != null)
groups.put(id, new ArrayList<Map.Entry<File, Report>>());
groups.get(id).add(rent);
}
for(ErrorIdentity id : groups.keySet()) {
out.println("<h2>" + htmlq(findrootexc(id.t).getClass().getSimpleName()) + "</h2>");
out.println("<table><tr>");
out.println(" <th>File</th>");
out.println(" <th>Time</th>");
out.println(" <th>Exception</th>");
for(String pn : props)
out.println(" <th>" + htmlq(pn) + "</th>");
out.println("</tr>");
List<Map.Entry<File, Report>> reps = groups.get(id);
Collections.sort(reps, new Comparator<Map.Entry<File, Report>>() {
public int compare(Map.Entry<File, Report> a, Map.Entry<File, Report> b) {
long at = a.getValue().time, bt = b.getValue().time;
if(at > bt)
return(-1);
else if(at < bt)
return(1);
else
return(0);
}
});
for(Map.Entry<File, Report> rent : reps) {
File file = rent.getKey();
Report rep = rent.getValue();
out.println(" <tr>");
out.print(" <td>");
out.println("<a href=\"" + htmlq(file.getName()) + ".html\">");
out.print(htmlq(file.getName()));
out.println("</a></td>");
out.println(" <td>" + htmlq(dfmt.format(new Date(rep.time))) + "</td>");
out.println(" <td>" + htmlq(findrootexc(rep.t).getClass().getSimpleName()) + "</td>");
for(String pn : props) {
out.print(" <td>");
if(rep.props.containsKey(pn)) {
out.print(htmlq(rep.props.get(pn).toString()));
}
out.println("</td>");
}
out.println(" </tr>");
}
out.println("</table>");
}
if(failed.size() > 0) {
out.println("<h2>Unreadable reports</h2>");
out.println("<table>");
out.println("<tr><th>File</th><th>Exception</th>");
for(File file : failed.keySet()) {
Exception exc = failed.get(file);
out.print(" <tr>");
out.print("<td>" + htmlq(file.getName()) + "</td><td>" + htmlq(exc.getClass().getName()) + ": " + htmlq(exc.getMessage()) + "</td>");
out.println(" </tr>");
}
out.println("</table>");
}
out.print(htmltail());
out.flush();
}
| public static void makeindex(OutputStream outs, Map<File, Report> reports, Map<File, Exception> failed) throws IOException {
PrintWriter out = new PrintWriter(new OutputStreamWriter(outs, "UTF-8"));
out.print(htmlhead("Error Index"));
out.println("<h1>Error Index</h1>");
Set<String> props = new TreeSet<String>();
for(String pn : idxprops)
props.add(pn);
Map<ErrorIdentity, List<Map.Entry<File, Report>>> groups = new TreeMap<ErrorIdentity, List<Map.Entry<File, Report>>>();
for(Map.Entry<File, Report> rent : reports.entrySet()) {
ErrorIdentity id = new ErrorIdentity(rent.getValue());
if(groups.get(id) == null)
groups.put(id, new ArrayList<Map.Entry<File, Report>>());
groups.get(id).add(rent);
}
for(ErrorIdentity id : groups.keySet()) {
out.println("<h2>" + htmlq(findrootexc(id.t).getClass().getSimpleName()) + "</h2>");
out.println("<table><tr>");
out.println(" <th>File</th>");
out.println(" <th>Time</th>");
out.println(" <th>Exception</th>");
for(String pn : props)
out.println(" <th>" + htmlq(pn) + "</th>");
out.println("</tr>");
List<Map.Entry<File, Report>> reps = groups.get(id);
Collections.sort(reps, new Comparator<Map.Entry<File, Report>>() {
public int compare(Map.Entry<File, Report> a, Map.Entry<File, Report> b) {
long at = a.getValue().time, bt = b.getValue().time;
if(at > bt)
return(-1);
else if(at < bt)
return(1);
else
return(0);
}
});
for(Map.Entry<File, Report> rent : reps) {
File file = rent.getKey();
Report rep = rent.getValue();
out.println(" <tr>");
out.print(" <td>");
out.println("<a href=\"" + htmlq(file.getName()) + ".html\">");
out.print(htmlq(file.getName()));
out.println("</a></td>");
out.println(" <td>" + htmlq(dfmt.format(new Date(rep.time))) + "</td>");
out.println(" <td>" + htmlq(findrootexc(rep.t).getClass().getSimpleName()) + "</td>");
for(String pn : props) {
out.print(" <td>");
if(rep.props.containsKey(pn)) {
out.print(htmlq(rep.props.get(pn).toString()));
}
out.println("</td>");
}
out.println(" </tr>");
}
out.println("</table>");
}
if(failed.size() > 0) {
out.println("<h2>Unreadable reports</h2>");
out.println("<table>");
out.println("<tr><th>File</th><th>Exception</th>");
for(File file : failed.keySet()) {
Exception exc = failed.get(file);
out.print(" <tr>");
out.print("<td>" + htmlq(file.getName()) + "</td><td>" + htmlq(exc.getClass().getName()) + ": " + htmlq(exc.getMessage()) + "</td>");
out.println(" </tr>");
}
out.println("</table>");
}
out.print(htmltail());
out.flush();
}
|
diff --git a/src/com/fruit/launcher/DockButton.java b/src/com/fruit/launcher/DockButton.java
index 414657d..db01a76 100644
--- a/src/com/fruit/launcher/DockButton.java
+++ b/src/com/fruit/launcher/DockButton.java
@@ -1,426 +1,429 @@
package com.fruit.launcher;
import com.fruit.launcher.LauncherSettings.Applications;
import com.fruit.launcher.LauncherSettings.BaseLauncherColumns;
import com.fruit.launcher.LauncherSettings.Favorites;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.net.URISyntaxException;
public class DockButton extends ImageView implements DropTarget, DragSource,
LauncherMonitor.InfoCallback {
private static final String TAG = "DockButton";
public boolean mIsEmpty;
public boolean mIsHold;
public boolean mIsHome;
private Launcher mLauncher;
private ShortcutInfo mBackupDockButtonInfo;
private Paint mTrashPaint;
private Paint mPaint;
private Bitmap mCueBitmap;
private CueNumber mCueNumber;
public DockButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mIsEmpty = true;
mIsHold = false;
mIsHome = false;
mLauncher = null;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(18);
mPaint.setTypeface(Typeface.SANS_SERIF);
mCueNumber = new CueNumber();
mCueNumber.mbNumber = false;
mCueNumber.mMonitorType = LauncherMonitor.MONITOR_NONE;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mCueNumber.mbNumber) {
mCueNumber.drawCueNumber(canvas, mPaint, this.getWidth(), this.getHeight(),
mCueBitmap);
}
}
public void setDrawCueNumberState(boolean draw, int type) {
if (draw) {
if (mCueBitmap == null) {
BitmapDrawable drawable = (BitmapDrawable) getResources()
.getDrawable(R.drawable.ic_cue_bg);
mCueBitmap = drawable.getBitmap();
}
if (mLauncher != null) {
mLauncher.registerMonitor(type, this);
}
} else {
if (mLauncher != null) {
mLauncher.unregisterMonitor(type, this);
}
}
mCueNumber.mMonitorType = type;
mCueNumber.mbNumber = draw;
}
@Override
public boolean acceptDrop(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
// TODO Auto-generated method stub
final int itemType = ((ItemInfo) dragInfo).itemType;
// Only support ITEM_TYPE_APPLICATION and ITEM_TYPE_SHORTCUT
return (itemType == BaseLauncherColumns.ITEM_TYPE_APPLICATION
|| itemType == BaseLauncherColumns.ITEM_TYPE_SHORTCUT
|| itemType == Applications.APPS_TYPE_APP || itemType == Applications.APPS_TYPE_FOLDERAPP);
}
@Override
public void onDrop(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDrop");
// TODO Auto-generated method stub
final int itemType = ((ItemInfo) dragInfo).itemType;
final int index = ((DockBar.LayoutParams) getLayoutParams()).index;
final Workspace workspace = mLauncher.getWorkspace();
CellLayout current = (CellLayout) workspace.getChildAt(workspace
.getCurrentScreen());
if (itemType == Applications.APPS_TYPE_APP
|| itemType == Applications.APPS_TYPE_FOLDERAPP) {
ApplicationInfoEx appInfo = (ApplicationInfoEx) dragInfo;
ShortcutInfo dockItemInfo = mLauncher.getLauncherModel()
.getShortcutInfo(mLauncher.getPackageManager(),
appInfo.intent, getContext());
dockItemInfo.setActivity(appInfo.intent.getComponent(),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
setImageBitmap(Utilities.createCompoundBitmapEx(
dockItemInfo.title.toString(),
dockItemInfo.getIcon(mLauncher.getIconCache())));
dockItemInfo.container = Favorites.CONTAINER_DOCKBAR;
dockItemInfo.screen = -1;
dockItemInfo.cellX = index;
dockItemInfo.cellY = -1;
if (mIsEmpty) {
// Insert a new record to db, and got a new item id
LauncherModel.addItemToDatabase(mLauncher, dockItemInfo,
Favorites.CONTAINER_DOCKBAR, dockItemInfo.screen,
dockItemInfo.cellX, dockItemInfo.cellY, false);
mIsEmpty = false;
} else {
// Use old dock item's id
dockItemInfo.id = ((ShortcutInfo) getTag()).id;
LauncherModel.updateItemInDatabase(mLauncher, dockItemInfo);
}
setTag(dockItemInfo);
return;
}
if (mIsEmpty) {
ShortcutInfo appInfo = (ShortcutInfo) dragInfo;
if (appInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == appInfo.container) {
// Drag from user folder
mLauncher.removeItemFromFolder(appInfo);
}
}
setImageBitmap(Utilities.createCompoundBitmapEx(
appInfo.title.toString(),
appInfo.getIcon(mLauncher.getIconCache())));
mIsEmpty = false;
appInfo.cellX = index;
appInfo.cellY = -1;
appInfo.container = Favorites.CONTAINER_DOCKBAR;
appInfo.screen = -1;
setTag(appInfo);
LauncherModel.updateItemInDatabase(mLauncher, appInfo);
Log.d(TAG,
"dockbar, mIsEmpty,current has " + current.getChildCount()
+ " children");
} else {
ShortcutInfo deskItemInfo = (ShortcutInfo) dragInfo;
ShortcutInfo dockIteminfo = (ShortcutInfo) getTag();
if (source instanceof Workspace) {
deskItemInfo.cellX = workspace.getmDragInfo().cellX;
deskItemInfo.cellY = workspace.getmDragInfo().cellY;
}
if (deskItemInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == deskItemInfo.container) {
// Drag from user folder
// Remove this code block to add userfolder icon can
// exchange with dockbar
/*
* mLauncher.removeItemFromFolder(deskItemInfo);
* LauncherModel.deleteItemFromDatabase(mContext,
* dockIteminfo);
*
* deskItemInfo.cellX = index; deskItemInfo.cellY = -1;
* deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
* deskItemInfo.screen = -1;
* LauncherModel.updateItemInDatabase(mLauncher,
* deskItemInfo);
* setImageBitmap(Utilities.createCompoundBitmapEx
* (deskItemInfo.title.toString(),
* deskItemInfo.getIcon(mLauncher.getIconCache())));
* setTag(deskItemInfo); return;
*/
}
}
// Switch position of two items
/*
* if ((source instanceof Workspace) && current.isFull()) { int
* newCell[] = new int[2]; int scrn = workspace.getCurrentScreen();
* int number = current.findLastVacantCell(); if (number < 0) { scrn
* = deskItemInfo.screen; CellLayout temp = (CellLayout)
* workspace.getChildAt(scrn); number = temp.findLastVacantCell(); }
*
* current.numberToCell(number, newCell);
*
* dockIteminfo.cellX = newCell[0];//deskItemInfo.cellX;
* dockIteminfo.cellY = newCell[1];//deskItemInfo.cellY;
* dockIteminfo.screen = scrn;//deskItemInfo.screen; } else
*/{
dockIteminfo.cellX = deskItemInfo.cellX;
dockIteminfo.cellY = deskItemInfo.cellY;
- dockIteminfo.screen = workspace.getOriLayout().getPageIndex();// deskItemInfo.screen;
+ if(source instanceof DockButton)
+ dockIteminfo.screen = -1;
+ else
+ dockIteminfo.screen = workspace.getOriLayout().getPageIndex();// deskItemInfo.screen;
}
dockIteminfo.container = deskItemInfo.container;
dockIteminfo.orderId = deskItemInfo.orderId;
LauncherModel.updateItemInDatabase(mLauncher, dockIteminfo);
deskItemInfo.cellX = index;
deskItemInfo.cellY = -1;
deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
deskItemInfo.screen = -1;
LauncherModel.updateItemInDatabase(mLauncher, deskItemInfo);
setImageBitmap(Utilities.createCompoundBitmapEx(
deskItemInfo.title.toString(),
deskItemInfo.getIcon(mLauncher.getIconCache())));
setTag(deskItemInfo);
if (dockIteminfo.screen == -1) {
// Switch dock button
final DockBar dockBar = (DockBar) getParent();
DockButton view = (DockButton) dockBar
.getChildAt(dockIteminfo.cellX);
// view.setImageBitmap(dockIteminfo.getIcon(mLauncher.getIconCache()));
view.setImageBitmap(Utilities.createCompoundBitmapEx(
dockIteminfo.title.toString(),
dockIteminfo.getIcon(mLauncher.getIconCache())));
view.setTag(dockIteminfo);
view.mIsEmpty = false;
} else if (dockIteminfo.container != Favorites.CONTAINER_DESKTOP) {
// Drag from Folder to Dock bar
FolderInfo folderInfo = ((Folder) source).mInfo;
CellLayout cellLayout = (CellLayout) workspace
.getChildAt(folderInfo.screen);
for (int i = 0; i < cellLayout.getChildCount(); i++) {
ItemInfo itemInfo = (ItemInfo) cellLayout.getChildAt(i)
.getTag();
if (itemInfo != null && folderInfo.id == itemInfo.id) {
((FolderIcon) cellLayout.getChildAt(i))
.addItemInfo(dockIteminfo);
// ((FolderIcon)
// cellLayout.getChildAt(i)).refreshFolderIcon();
}
}
// if (source instanceof UserFolder) {
// UserFolder uf = (UserFolder)source;
// uf.
// }
} else {
// Drag from workspace to Dock bar
final View shortcut = mLauncher
.createShortcut(
R.layout.application,
(ViewGroup) workspace.getChildAt(workspace
.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace
* .
* getCurrentScreen
* (
* )
*//*
* dockIteminfo
* .
* screen
*/),
dockIteminfo);
// Log.d(TAG,"dockbar, before addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
workspace.addInScreen(shortcut,
workspace.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace.
* getCurrentScreen
* ()
*//*
* dockIteminfo.
* screen
*/,
dockIteminfo.cellX, dockIteminfo.cellY, 1, 1, false);
// Log.d(TAG,"dockbar, after addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
}
}
}
@Override
public void onDropCompleted(View target, boolean success) {
Log.d(TAG, "drag sequence,dockbutton onDropCompleted");
// TODO Auto-generated method stub
if (!success) {
setImageBitmap(mBackupDockButtonInfo.getIcon(mLauncher
.getIconCache()));
mIsEmpty = false;
setTag(mBackupDockButtonInfo);
LauncherModel
.updateItemInDatabase(mLauncher, mBackupDockButtonInfo);
}
mBackupDockButtonInfo = null;
}
@Override
public void onDragEnter(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDragEnter");
// TODO Auto-generated method stub
if (!acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
return;
}
if (mIsHold && mLauncher != null && !mLauncher.isAllAppsVisible()) {
return;
}
dragView.setPaint(mTrashPaint);
}
@Override
public void onDragOver(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDragOver");
// TODO Auto-generated method stub
}
@Override
public void onDragExit(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDragExit");
// TODO Auto-generated method stub
Log.d(TAG, "dragview exit,width=" + dragView.getWidth() + ",height="
+ dragView.getHeight());
dragView.setPaint(null);
}
@Override
public Rect estimateDropLocation(DragSource source, int x, int y,
int xOffset, int yOffset, DragView dragView, Object dragInfo,
Rect recycle) {
// TODO Auto-generated method stub
return null;
}
public void setLauncher(Launcher launcher) {
mLauncher = launcher;
}
@Override
public void setDragController(DragController dragger) {
}
public void setPaint(Paint paint) {
mTrashPaint = paint;
}
public void setDockButtonInfo(ShortcutInfo info) {
mBackupDockButtonInfo = info;
}
public void setTag(ShortcutInfo info) {
// cancel previous state;
if (mTag != null && mTag instanceof ShortcutInfo) {
ShortcutInfo preInfo = (ShortcutInfo) mTag;
if (preInfo.intent != null
&& mCueNumber.getMonitorType(preInfo.intent) != LauncherMonitor.MONITOR_NONE) {
setDrawCueNumberState(false, mCueNumber.mMonitorType);
}
}
super.setTag(info);
// set new state
if (info != null && info.intent != null) {
int type = mCueNumber.getMonitorType(info.intent);
if (type != LauncherMonitor.MONITOR_NONE) {
setDrawCueNumberState(true, type);
}
}
}
@Override
public void onInfoCountChanged(int number) {
// TODO Auto-generated method stub
if (number <= 0) {
mCueNumber.mCueNum = null;
return;
} else if (number >= 100) {
mCueNumber.mCueNum = new String(CueNumber.CUE_MAX);
} else {
mCueNumber.mCueNum = String.valueOf(number);
}
invalidate();
}
// /* (non-Javadoc)
// * @see android.widget.ImageView#setImageBitmap(android.graphics.Bitmap)
// */
// @Override
// public void setImageBitmap(Bitmap bm) {
// // TODO Auto-generated method stub
// //Bitmap icon = Utilities.changeBitmap4Launcher(bm);
// super.setImageBitmap(bm);
// }
}
| true | true | public void onDrop(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDrop");
// TODO Auto-generated method stub
final int itemType = ((ItemInfo) dragInfo).itemType;
final int index = ((DockBar.LayoutParams) getLayoutParams()).index;
final Workspace workspace = mLauncher.getWorkspace();
CellLayout current = (CellLayout) workspace.getChildAt(workspace
.getCurrentScreen());
if (itemType == Applications.APPS_TYPE_APP
|| itemType == Applications.APPS_TYPE_FOLDERAPP) {
ApplicationInfoEx appInfo = (ApplicationInfoEx) dragInfo;
ShortcutInfo dockItemInfo = mLauncher.getLauncherModel()
.getShortcutInfo(mLauncher.getPackageManager(),
appInfo.intent, getContext());
dockItemInfo.setActivity(appInfo.intent.getComponent(),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
setImageBitmap(Utilities.createCompoundBitmapEx(
dockItemInfo.title.toString(),
dockItemInfo.getIcon(mLauncher.getIconCache())));
dockItemInfo.container = Favorites.CONTAINER_DOCKBAR;
dockItemInfo.screen = -1;
dockItemInfo.cellX = index;
dockItemInfo.cellY = -1;
if (mIsEmpty) {
// Insert a new record to db, and got a new item id
LauncherModel.addItemToDatabase(mLauncher, dockItemInfo,
Favorites.CONTAINER_DOCKBAR, dockItemInfo.screen,
dockItemInfo.cellX, dockItemInfo.cellY, false);
mIsEmpty = false;
} else {
// Use old dock item's id
dockItemInfo.id = ((ShortcutInfo) getTag()).id;
LauncherModel.updateItemInDatabase(mLauncher, dockItemInfo);
}
setTag(dockItemInfo);
return;
}
if (mIsEmpty) {
ShortcutInfo appInfo = (ShortcutInfo) dragInfo;
if (appInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == appInfo.container) {
// Drag from user folder
mLauncher.removeItemFromFolder(appInfo);
}
}
setImageBitmap(Utilities.createCompoundBitmapEx(
appInfo.title.toString(),
appInfo.getIcon(mLauncher.getIconCache())));
mIsEmpty = false;
appInfo.cellX = index;
appInfo.cellY = -1;
appInfo.container = Favorites.CONTAINER_DOCKBAR;
appInfo.screen = -1;
setTag(appInfo);
LauncherModel.updateItemInDatabase(mLauncher, appInfo);
Log.d(TAG,
"dockbar, mIsEmpty,current has " + current.getChildCount()
+ " children");
} else {
ShortcutInfo deskItemInfo = (ShortcutInfo) dragInfo;
ShortcutInfo dockIteminfo = (ShortcutInfo) getTag();
if (source instanceof Workspace) {
deskItemInfo.cellX = workspace.getmDragInfo().cellX;
deskItemInfo.cellY = workspace.getmDragInfo().cellY;
}
if (deskItemInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == deskItemInfo.container) {
// Drag from user folder
// Remove this code block to add userfolder icon can
// exchange with dockbar
/*
* mLauncher.removeItemFromFolder(deskItemInfo);
* LauncherModel.deleteItemFromDatabase(mContext,
* dockIteminfo);
*
* deskItemInfo.cellX = index; deskItemInfo.cellY = -1;
* deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
* deskItemInfo.screen = -1;
* LauncherModel.updateItemInDatabase(mLauncher,
* deskItemInfo);
* setImageBitmap(Utilities.createCompoundBitmapEx
* (deskItemInfo.title.toString(),
* deskItemInfo.getIcon(mLauncher.getIconCache())));
* setTag(deskItemInfo); return;
*/
}
}
// Switch position of two items
/*
* if ((source instanceof Workspace) && current.isFull()) { int
* newCell[] = new int[2]; int scrn = workspace.getCurrentScreen();
* int number = current.findLastVacantCell(); if (number < 0) { scrn
* = deskItemInfo.screen; CellLayout temp = (CellLayout)
* workspace.getChildAt(scrn); number = temp.findLastVacantCell(); }
*
* current.numberToCell(number, newCell);
*
* dockIteminfo.cellX = newCell[0];//deskItemInfo.cellX;
* dockIteminfo.cellY = newCell[1];//deskItemInfo.cellY;
* dockIteminfo.screen = scrn;//deskItemInfo.screen; } else
*/{
dockIteminfo.cellX = deskItemInfo.cellX;
dockIteminfo.cellY = deskItemInfo.cellY;
dockIteminfo.screen = workspace.getOriLayout().getPageIndex();// deskItemInfo.screen;
}
dockIteminfo.container = deskItemInfo.container;
dockIteminfo.orderId = deskItemInfo.orderId;
LauncherModel.updateItemInDatabase(mLauncher, dockIteminfo);
deskItemInfo.cellX = index;
deskItemInfo.cellY = -1;
deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
deskItemInfo.screen = -1;
LauncherModel.updateItemInDatabase(mLauncher, deskItemInfo);
setImageBitmap(Utilities.createCompoundBitmapEx(
deskItemInfo.title.toString(),
deskItemInfo.getIcon(mLauncher.getIconCache())));
setTag(deskItemInfo);
if (dockIteminfo.screen == -1) {
// Switch dock button
final DockBar dockBar = (DockBar) getParent();
DockButton view = (DockButton) dockBar
.getChildAt(dockIteminfo.cellX);
// view.setImageBitmap(dockIteminfo.getIcon(mLauncher.getIconCache()));
view.setImageBitmap(Utilities.createCompoundBitmapEx(
dockIteminfo.title.toString(),
dockIteminfo.getIcon(mLauncher.getIconCache())));
view.setTag(dockIteminfo);
view.mIsEmpty = false;
} else if (dockIteminfo.container != Favorites.CONTAINER_DESKTOP) {
// Drag from Folder to Dock bar
FolderInfo folderInfo = ((Folder) source).mInfo;
CellLayout cellLayout = (CellLayout) workspace
.getChildAt(folderInfo.screen);
for (int i = 0; i < cellLayout.getChildCount(); i++) {
ItemInfo itemInfo = (ItemInfo) cellLayout.getChildAt(i)
.getTag();
if (itemInfo != null && folderInfo.id == itemInfo.id) {
((FolderIcon) cellLayout.getChildAt(i))
.addItemInfo(dockIteminfo);
// ((FolderIcon)
// cellLayout.getChildAt(i)).refreshFolderIcon();
}
}
// if (source instanceof UserFolder) {
// UserFolder uf = (UserFolder)source;
// uf.
// }
} else {
// Drag from workspace to Dock bar
final View shortcut = mLauncher
.createShortcut(
R.layout.application,
(ViewGroup) workspace.getChildAt(workspace
.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace
* .
* getCurrentScreen
* (
* )
*//*
* dockIteminfo
* .
* screen
*/),
dockIteminfo);
// Log.d(TAG,"dockbar, before addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
workspace.addInScreen(shortcut,
workspace.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace.
* getCurrentScreen
* ()
*//*
* dockIteminfo.
* screen
*/,
dockIteminfo.cellX, dockIteminfo.cellY, 1, 1, false);
// Log.d(TAG,"dockbar, after addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
}
}
| public void onDrop(DragSource source, int x, int y, int xOffset,
int yOffset, DragView dragView, Object dragInfo) {
Log.d(TAG, "drag sequence,dockbutton onDrop");
// TODO Auto-generated method stub
final int itemType = ((ItemInfo) dragInfo).itemType;
final int index = ((DockBar.LayoutParams) getLayoutParams()).index;
final Workspace workspace = mLauncher.getWorkspace();
CellLayout current = (CellLayout) workspace.getChildAt(workspace
.getCurrentScreen());
if (itemType == Applications.APPS_TYPE_APP
|| itemType == Applications.APPS_TYPE_FOLDERAPP) {
ApplicationInfoEx appInfo = (ApplicationInfoEx) dragInfo;
ShortcutInfo dockItemInfo = mLauncher.getLauncherModel()
.getShortcutInfo(mLauncher.getPackageManager(),
appInfo.intent, getContext());
dockItemInfo.setActivity(appInfo.intent.getComponent(),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
setImageBitmap(Utilities.createCompoundBitmapEx(
dockItemInfo.title.toString(),
dockItemInfo.getIcon(mLauncher.getIconCache())));
dockItemInfo.container = Favorites.CONTAINER_DOCKBAR;
dockItemInfo.screen = -1;
dockItemInfo.cellX = index;
dockItemInfo.cellY = -1;
if (mIsEmpty) {
// Insert a new record to db, and got a new item id
LauncherModel.addItemToDatabase(mLauncher, dockItemInfo,
Favorites.CONTAINER_DOCKBAR, dockItemInfo.screen,
dockItemInfo.cellX, dockItemInfo.cellY, false);
mIsEmpty = false;
} else {
// Use old dock item's id
dockItemInfo.id = ((ShortcutInfo) getTag()).id;
LauncherModel.updateItemInDatabase(mLauncher, dockItemInfo);
}
setTag(dockItemInfo);
return;
}
if (mIsEmpty) {
ShortcutInfo appInfo = (ShortcutInfo) dragInfo;
if (appInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == appInfo.container) {
// Drag from user folder
mLauncher.removeItemFromFolder(appInfo);
}
}
setImageBitmap(Utilities.createCompoundBitmapEx(
appInfo.title.toString(),
appInfo.getIcon(mLauncher.getIconCache())));
mIsEmpty = false;
appInfo.cellX = index;
appInfo.cellY = -1;
appInfo.container = Favorites.CONTAINER_DOCKBAR;
appInfo.screen = -1;
setTag(appInfo);
LauncherModel.updateItemInDatabase(mLauncher, appInfo);
Log.d(TAG,
"dockbar, mIsEmpty,current has " + current.getChildCount()
+ " children");
} else {
ShortcutInfo deskItemInfo = (ShortcutInfo) dragInfo;
ShortcutInfo dockIteminfo = (ShortcutInfo) getTag();
if (source instanceof Workspace) {
deskItemInfo.cellX = workspace.getmDragInfo().cellX;
deskItemInfo.cellY = workspace.getmDragInfo().cellY;
}
if (deskItemInfo.container >= 0) {
if (source instanceof UserFolder
&& ((UserFolder) source).mInfo.id == deskItemInfo.container) {
// Drag from user folder
// Remove this code block to add userfolder icon can
// exchange with dockbar
/*
* mLauncher.removeItemFromFolder(deskItemInfo);
* LauncherModel.deleteItemFromDatabase(mContext,
* dockIteminfo);
*
* deskItemInfo.cellX = index; deskItemInfo.cellY = -1;
* deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
* deskItemInfo.screen = -1;
* LauncherModel.updateItemInDatabase(mLauncher,
* deskItemInfo);
* setImageBitmap(Utilities.createCompoundBitmapEx
* (deskItemInfo.title.toString(),
* deskItemInfo.getIcon(mLauncher.getIconCache())));
* setTag(deskItemInfo); return;
*/
}
}
// Switch position of two items
/*
* if ((source instanceof Workspace) && current.isFull()) { int
* newCell[] = new int[2]; int scrn = workspace.getCurrentScreen();
* int number = current.findLastVacantCell(); if (number < 0) { scrn
* = deskItemInfo.screen; CellLayout temp = (CellLayout)
* workspace.getChildAt(scrn); number = temp.findLastVacantCell(); }
*
* current.numberToCell(number, newCell);
*
* dockIteminfo.cellX = newCell[0];//deskItemInfo.cellX;
* dockIteminfo.cellY = newCell[1];//deskItemInfo.cellY;
* dockIteminfo.screen = scrn;//deskItemInfo.screen; } else
*/{
dockIteminfo.cellX = deskItemInfo.cellX;
dockIteminfo.cellY = deskItemInfo.cellY;
if(source instanceof DockButton)
dockIteminfo.screen = -1;
else
dockIteminfo.screen = workspace.getOriLayout().getPageIndex();// deskItemInfo.screen;
}
dockIteminfo.container = deskItemInfo.container;
dockIteminfo.orderId = deskItemInfo.orderId;
LauncherModel.updateItemInDatabase(mLauncher, dockIteminfo);
deskItemInfo.cellX = index;
deskItemInfo.cellY = -1;
deskItemInfo.container = Favorites.CONTAINER_DOCKBAR;
deskItemInfo.screen = -1;
LauncherModel.updateItemInDatabase(mLauncher, deskItemInfo);
setImageBitmap(Utilities.createCompoundBitmapEx(
deskItemInfo.title.toString(),
deskItemInfo.getIcon(mLauncher.getIconCache())));
setTag(deskItemInfo);
if (dockIteminfo.screen == -1) {
// Switch dock button
final DockBar dockBar = (DockBar) getParent();
DockButton view = (DockButton) dockBar
.getChildAt(dockIteminfo.cellX);
// view.setImageBitmap(dockIteminfo.getIcon(mLauncher.getIconCache()));
view.setImageBitmap(Utilities.createCompoundBitmapEx(
dockIteminfo.title.toString(),
dockIteminfo.getIcon(mLauncher.getIconCache())));
view.setTag(dockIteminfo);
view.mIsEmpty = false;
} else if (dockIteminfo.container != Favorites.CONTAINER_DESKTOP) {
// Drag from Folder to Dock bar
FolderInfo folderInfo = ((Folder) source).mInfo;
CellLayout cellLayout = (CellLayout) workspace
.getChildAt(folderInfo.screen);
for (int i = 0; i < cellLayout.getChildCount(); i++) {
ItemInfo itemInfo = (ItemInfo) cellLayout.getChildAt(i)
.getTag();
if (itemInfo != null && folderInfo.id == itemInfo.id) {
((FolderIcon) cellLayout.getChildAt(i))
.addItemInfo(dockIteminfo);
// ((FolderIcon)
// cellLayout.getChildAt(i)).refreshFolderIcon();
}
}
// if (source instanceof UserFolder) {
// UserFolder uf = (UserFolder)source;
// uf.
// }
} else {
// Drag from workspace to Dock bar
final View shortcut = mLauncher
.createShortcut(
R.layout.application,
(ViewGroup) workspace.getChildAt(workspace
.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace
* .
* getCurrentScreen
* (
* )
*//*
* dockIteminfo
* .
* screen
*/),
dockIteminfo);
// Log.d(TAG,"dockbar, before addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
workspace.addInScreen(shortcut,
workspace.getChildIndexByPageIndex(workspace
.getOriLayout().getPageIndex())/*
* workspace.
* getCurrentScreen
* ()
*//*
* dockIteminfo.
* screen
*/,
dockIteminfo.cellX, dockIteminfo.cellY, 1, 1, false);
// Log.d(TAG,"dockbar, after addInScreen,current has "+
// ((CellLayout)workspace.getChildAt(dockIteminfo.screen)).getChildCount()+" children");
}
}
|
diff --git a/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java b/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
index c30984cd..9868ae76 100644
--- a/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
+++ b/src/org/openstreetmap/josm/data/osm/visitor/MapPaintVisitor.java
@@ -1,1642 +1,1643 @@
/* License: GPL. Copyright 2007 by Immanuel Scholz and others */
package org.openstreetmap.josm.data.osm.visitor;
/* To enable debugging or profiling remove the double / signs */
import static org.openstreetmap.josm.tools.I18n.marktr;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.swing.ImageIcon;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.osm.BBox;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.osm.Node;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Relation;
import org.openstreetmap.josm.data.osm.RelationMember;
import org.openstreetmap.josm.data.osm.Way;
import org.openstreetmap.josm.gui.DefaultNameFormatter;
import org.openstreetmap.josm.gui.mappaint.AreaElemStyle;
import org.openstreetmap.josm.gui.mappaint.ElemStyle;
import org.openstreetmap.josm.gui.mappaint.ElemStyles;
import org.openstreetmap.josm.gui.mappaint.IconElemStyle;
import org.openstreetmap.josm.gui.mappaint.LineElemStyle;
import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.LanguageInfo;
public class MapPaintVisitor extends SimplePaintVisitor {
protected boolean useRealWidth;
protected boolean zoomLevelDisplay;
protected boolean drawMultipolygon;
protected boolean drawRestriction;
protected boolean leftHandTraffic;
//protected boolean restrictionDebug;
protected int showNames;
protected int showIcons;
protected int useStrokes;
protected int fillAlpha;
protected Color untaggedColor;
protected Color textColor;
protected Color areaTextColor;
protected float[] currentDashed = new float[0];
protected Color currentDashedColor;
protected int currentWidth = 0;
protected Stroke currentStroke = null;
protected Font orderFont;
protected ElemStyles.StyleSet styles;
protected double circum;
protected double dist;
protected Collection<String> regionalNameOrder;
protected boolean useStyleCache;
private static int paintid = 0;
private EastNorth minEN;
private EastNorth maxEN;
//protected int profilerVisibleNodes;
//protected int profilerVisibleWays;
//protected int profilerVisibleAreas;
//protected int profilerSegments;
//protected int profilerVisibleSegments;
//protected boolean profilerOmitDraw;
protected boolean isZoomOk(ElemStyle e) {
if (!zoomLevelDisplay) /* show everything if the user wishes so */
return true;
if(e == null) /* the default for things that don't have a rule (show, if scale is smaller than 1500m) */
return (circum < 1500);
return !(circum >= e.maxScale || circum < e.minScale);
}
public ElemStyle getPrimitiveStyle(OsmPrimitive osm) {
if(!useStyleCache)
return (styles != null) ? styles.get(osm) : null;
if(osm.mappaintStyle == null && styles != null) {
osm.mappaintStyle = styles.get(osm);
if(osm instanceof Way) {
((Way)osm).isMappaintArea = styles.isArea(osm);
}
}
return osm.mappaintStyle;
}
public IconElemStyle getPrimitiveNodeStyle(OsmPrimitive osm) {
if(!useStyleCache)
return (styles != null) ? styles.getIcon(osm) : null;
if(osm.mappaintStyle == null && styles != null) {
osm.mappaintStyle = styles.getIcon(osm);
}
return (IconElemStyle)osm.mappaintStyle;
}
public boolean isPrimitiveArea(Way osm) {
if(!useStyleCache)
return styles.isArea(osm);
if(osm.mappaintStyle == null && styles != null) {
osm.mappaintStyle = styles.get(osm);
osm.isMappaintArea = styles.isArea(osm);
}
return osm.isMappaintArea;
}
/**
* Draw a small rectangle.
* White if selected (as always) or red otherwise.
*
* @param n The node to draw.
*/
@Override
public void visit(Node n) {}
public void drawNode(Node n) {
/* check, if the node is visible at all */
if((n.getEastNorth().east() > maxEN.east() ) ||
(n.getEastNorth().north() > maxEN.north()) ||
(n.getEastNorth().east() < minEN.east() ) ||
(n.getEastNorth().north() < minEN.north()))
return;
IconElemStyle nodeStyle = (IconElemStyle)getPrimitiveStyle(n);
//if(profilerOmitDraw)
// return;
if (nodeStyle != null && isZoomOk(nodeStyle) && showIcons > dist) {
if (inactive || n.isDisabled()) {
drawNode(n, nodeStyle.getDisabledIcon(), nodeStyle.annotate, data.isSelected(n));
} else {
drawNode(n, nodeStyle.icon, nodeStyle.annotate, data.isSelected(n));
}
} else if (n.highlighted) {
drawNode(n, highlightColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
} else if (data.isSelected(n)) {
drawNode(n, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
} else if (n.isTagged()) {
drawNode(n, nodeColor, taggedNodeSize, taggedNodeRadius, fillUnselectedNode);
} else if (inactive || n.isDisabled()) {
drawNode(n, inactiveColor, unselectedNodeSize, unselectedNodeRadius, fillUnselectedNode);
} else {
drawNode(n, nodeColor, unselectedNodeSize, unselectedNodeRadius, fillUnselectedNode);
}
}
/**
* Draw a line for all segments, according to tags.
* @param w The way to draw.
*/
@Override
public void visit(Way w) {}
public void drawWay(Way w, int fillAreas) {
if(w.getNodesCount() < 2)
return;
/* check, if the way is visible at all */
double minx = 10000;
double maxx = -10000;
double miny = 10000;
double maxy = -10000;
for (Node n : w.getNodes())
{
if(n.getEastNorth().east() > maxx) {
maxx = n.getEastNorth().east();
}
if(n.getEastNorth().north() > maxy) {
maxy = n.getEastNorth().north();
}
if(n.getEastNorth().east() < minx) {
minx = n.getEastNorth().east();
}
if(n.getEastNorth().north() < miny) {
miny = n.getEastNorth().north();
}
}
if ((minx > maxEN.east()) ||
(miny > maxEN.north()) ||
(maxx < minEN.east()) ||
(maxy < minEN.north()))
return;
ElemStyle wayStyle = getPrimitiveStyle(w);
if(!isZoomOk(wayStyle))
return;
if(wayStyle==null)
{
/* way without style */
//profilerVisibleWays++;
//if(!profilerOmitDraw)
drawWay(w, null, untaggedColor, data.isSelected(w));
}
else if(wayStyle instanceof LineElemStyle)
{
/* way with line style */
//profilerVisibleWays++;
//if(!profilerOmitDraw)
drawWay(w, (LineElemStyle)wayStyle, untaggedColor, data.isSelected(w));
}
else if (wayStyle instanceof AreaElemStyle)
{
AreaElemStyle areaStyle = (AreaElemStyle) wayStyle;
/* way with area style */
//if(!profilerOmitDraw)
//{
if (fillAreas > dist)
{
// profilerVisibleAreas++;
drawArea(w, data.isSelected(w) ? selectedColor : areaStyle.color);
if(!w.isClosed()) {
putError(w, tr("Area style way is not closed."), true);
}
}
drawWay(w, areaStyle.line, areaStyle.color, data.isSelected(w));
//}
}
}
public void drawWay(Way w, LineElemStyle l, Color color, boolean selected) {
/* show direction arrows, if draw.segment.relevant_directions_only is not set,
the way is tagged with a direction key
(even if the tag is negated as in oneway=false) or the way is selected */
boolean showDirection = data.isSelected(w) || ((!useRealWidth) && (showDirectionArrow
&& (!showRelevantDirectionsOnly || w.hasDirectionKeys())));
/* head only takes over control if the option is true,
the direction should be shown at all and not only because it's selected */
boolean showOnlyHeadArrowOnly = showDirection && !data.isSelected(w) && showHeadArrowOnly;
int width = defaultSegmentWidth;
int realWidth = 0; /* the real width of the element in meters */
float dashed[] = new float[0];
Color dashedColor = null;
Node lastN;
if(l != null)
{
if (l.color != null) {
color = l.color;
}
width = l.width;
realWidth = l.realWidth;
dashed = l.dashed;
dashedColor = l.dashedColor;
}
if(selected) {
color = selectedColor;
}
if (realWidth > 0 && useRealWidth && !showDirection)
{
int tmpWidth = (int) (100 / (float) (circum / realWidth));
if (tmpWidth > width) {
width = tmpWidth;
}
/* if we have a "width" tag, try use it */
/* (this might be slow and could be improved by caching the value in the Way, on the other hand only used if "real width" is enabled) */
String widthTag = w.get("width");
if(widthTag == null) {
widthTag = w.get("est_width");
}
if(widthTag != null) {
try {
width = Integer.parseInt(widthTag);
}
catch(NumberFormatException nfe) {
}
}
}
if(w.highlighted) {
color = highlightColor;
} else if(data.isSelected(w)) {
color = selectedColor;
} else if(w.isDisabled()) {
color = inactiveColor;
}
/* draw overlays under the way */
if(l != null && l.overlays != null)
{
for(LineElemStyle s : l.overlays)
{
if(!s.over)
{
lastN = null;
for(Node n : w.getNodes())
{
if(lastN != null)
{
drawSeg(lastN, n, s.color != null && !data.isSelected(w) ? s.color : color,
false, s.getWidth(width), s.dashed, s.dashedColor);
}
lastN = n;
}
}
}
}
/* draw the way */
lastN = null;
Iterator<Node> it = w.getNodes().iterator();
while (it.hasNext())
{
Node n = it.next();
if(lastN != null) {
drawSeg(lastN, n, color,
showOnlyHeadArrowOnly ? !it.hasNext() : showDirection, width, dashed, dashedColor);
}
lastN = n;
}
/* draw overlays above the way */
if(l != null && l.overlays != null)
{
for(LineElemStyle s : l.overlays)
{
if(s.over)
{
lastN = null;
for(Node n : w.getNodes())
{
if(lastN != null)
{
drawSeg(lastN, n, s.color != null && !data.isSelected(w) ? s.color : color,
false, s.getWidth(width), s.dashed, s.dashedColor);
}
lastN = n;
}
}
}
}
if(showOrderNumber)
{
int orderNumber = 0;
lastN = null;
for(Node n : w.getNodes())
{
if(lastN != null)
{
orderNumber++;
drawOrderNumber(lastN, n, orderNumber);
}
lastN = n;
}
}
displaySegments();
}
public Collection<PolyData> joinWays(Collection<Way> join, OsmPrimitive errs)
{
Collection<PolyData> res = new LinkedList<PolyData>();
Object[] joinArray = join.toArray();
int left = join.size();
while(left != 0)
{
Way w = null;
boolean selected = false;
List<Node> n = null;
boolean joined = true;
while(joined && left != 0)
{
joined = false;
for(int i = 0; i < joinArray.length && left != 0; ++i)
{
if(joinArray[i] != null)
{
Way c = (Way)joinArray[i];
if(w == null)
{ w = c; selected = data.isSelected(w); joinArray[i] = null; --left; }
else
{
int mode = 0;
int cl = c.getNodesCount()-1;
int nl;
if(n == null)
{
nl = w.getNodesCount()-1;
if(w.getNode(nl) == c.getNode(0)) {
mode = 21;
} else if(w.getNode(nl) == c.getNode(cl)) {
mode = 22;
} else if(w.getNode(0) == c.getNode(0)) {
mode = 11;
} else if(w.getNode(0) == c.getNode(cl)) {
mode = 12;
}
}
else
{
nl = n.size()-1;
if(n.get(nl) == c.getNode(0)) {
mode = 21;
} else if(n.get(0) == c.getNode(cl)) {
mode = 12;
} else if(n.get(0) == c.getNode(0)) {
mode = 11;
} else if(n.get(nl) == c.getNode(cl)) {
mode = 22;
}
}
if(mode != 0)
{
joinArray[i] = null;
joined = true;
if(data.isSelected(c)) {
selected = true;
}
--left;
if(n == null) {
n = w.getNodes();
}
n.remove((mode == 21 || mode == 22) ? nl : 0);
if(mode == 21) {
n.addAll(c.getNodes());
} else if(mode == 12) {
n.addAll(0, c.getNodes());
} else if(mode == 22)
{
for(Node node : c.getNodes()) {
n.add(nl, node);
}
}
else /* mode == 11 */
{
for(Node node : c.getNodes()) {
n.add(0, node);
}
}
}
}
}
} /* for(i = ... */
} /* while(joined) */
if(n != null)
{
w = new Way(w);
w.setNodes(n);
// Do not mess with the DataSet's contents here.
}
if(!w.isClosed())
{
if(errs != null)
{
putError(errs, tr("multipolygon way ''{0}'' is not closed.",
w.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
}
PolyData pd = new PolyData(w);
pd.selected = selected;
res.add(pd);
} /* while(left != 0) */
return res;
}
public void drawSelectedMember(OsmPrimitive osm, ElemStyle style, boolean area,
boolean areaselected)
{
if(osm instanceof Way)
{
if(style instanceof AreaElemStyle)
{
Way way = (Way)osm;
AreaElemStyle areaStyle = (AreaElemStyle)style;
drawWay(way, areaStyle.line, selectedColor, true);
if(area) {
drawArea(way, areaselected ? selectedColor : areaStyle.color);
}
}
else
{
drawWay((Way)osm, (LineElemStyle)style, selectedColor, true);
}
}
else if(osm instanceof Node)
{
if(style != null && isZoomOk(style)) {
drawNode((Node)osm, ((IconElemStyle)style).icon,
((IconElemStyle)style).annotate, true);
} else {
drawNode((Node)osm, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
}
}
osm.mappaintDrawnCode = paintid;
}
@Override
public void visit(Relation r) {}
public void paintUnselectedRelation(Relation r) {
if (drawMultipolygon && "multipolygon".equals(r.get("type")))
{
if(drawMultipolygon(r))
return;
}
else if (drawRestriction && "restriction".equals(r.get("type")))
{
drawRestriction(r);
}
if(data.isSelected(r)) /* draw ways*/
{
for (RelationMember m : r.getMembers())
{
if (m.isWay() && drawable(m.getMember()))
{
drawSelectedMember(m.getMember(), styles != null ? getPrimitiveStyle(m.getMember())
: null, true, true);
}
}
}
}
/* this current experimental implementation will only work for standard restrictions:
from(Way) / via(Node) / to(Way) */
public void drawRestriction(Relation r) {
//if(restrictionDebug)
// System.out.println("Restriction: " + r.keys.get("name") + " restriction " + r.keys.get("restriction"));
Way fromWay = null;
Way toWay = null;
OsmPrimitive via = null;
/* find the "from", "via" and "to" elements */
for (RelationMember m : r.getMembers())
{
//if(restrictionDebug)
// System.out.println("member " + m.member + " selected " + r.selected);
if (m.getMember().isDeleted()) {
putError(r, tr("Deleted member ''{0}'' in relation.",
m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
} else if(m.getMember().incomplete)
return;
else
{
if(m.isWay())
{
Way w = m.getWay();
if(w.getNodesCount() < 2)
{
putError(r, tr("Way ''{0}'' with less than two points.",
w.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
else if("from".equals(m.getRole())) {
if(fromWay != null) {
putError(r, tr("More than one \"from\" way found."), true);
} else {
fromWay = w;
}
} else if("to".equals(m.getRole())) {
if(toWay != null) {
putError(r, tr("More than one \"to\" way found."), true);
} else {
toWay = w;
}
} else if("via".equals(m.getRole())) {
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = w;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
}
else if(m.isNode())
{
Node n = m.getNode();
if("via".equals(m.getRole()))
{
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = n;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
} else {
putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
}
}
}
if (fromWay == null) {
putError(r, tr("No \"from\" way found."), true);
return;
}
if (toWay == null) {
putError(r, tr("No \"to\" way found."), true);
return;
}
if (via == null) {
putError(r, tr("No \"via\" node or way found."), true);
return;
}
Node viaNode;
if(via instanceof Node)
{
viaNode = (Node) via;
if(!fromWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"from\" way doesn't start or end at a \"via\" node."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"to\" way doesn't start or end at a \"via\" node."), true);
}
}
else
{
Way viaWay = (Way) via;
Node firstNode = viaWay.firstNode();
Node lastNode = viaWay.lastNode();
boolean onewayvia = false;
String onewayviastr = viaWay.get("oneway");
if(onewayviastr != null)
{
if("-1".equals(onewayviastr)) {
onewayvia = true;
+ Node tmp = firstNode;
firstNode = lastNode;
- lastNode = firstNode;
+ lastNode = tmp;
} else {
onewayvia = OsmUtils.getOsmBoolean(onewayviastr);
}
}
if(fromWay.isFirstLastNode(firstNode)) {
viaNode = firstNode;
} else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
viaNode = lastNode;
} else {
putError(r, tr("The \"from\" way doesn't start or end at the \"via\" way."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) {
putError(r, tr("The \"to\" way doesn't start or end at the \"via\" way."), true);
}
}
/* find the "direct" nodes before the via node */
Node fromNode = null;
if(fromWay.firstNode() == via) {
//System.out.println("From way heading away from via");
fromNode = fromWay.getNode(1);
} else {
//System.out.println("From way heading towards via");
fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
}
Point pFrom = nc.getPoint(fromNode);
Point pVia = nc.getPoint(viaNode);
//if(restrictionDebug) {
/* find the "direct" node after the via node */
// Node toNode = null;
// if(toWay.firstNode() == via) {
// System.out.println("To way heading away from via");
// toNode = toWay.nodes.get(1);
// } else {
// System.out.println("To way heading towards via");
// toNode = toWay.nodes.get(toWay.nodes.size()-2);
// }
// Point pTo = nc.getPoint(toNode);
// /* debug output of interesting nodes */
// System.out.println("From: " + fromNode);
// drawNode(fromNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("Via: " + via);
// drawNode(via, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("To: " + toNode);
// drawNode(toNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("From X: " + pFrom.x + " Y " + pFrom.y);
// System.out.println("Via X: " + pVia.x + " Y " + pVia.y);
// System.out.println("To X: " + pTo.x + " Y " + pTo.y);
//}
/* starting from via, go back the "from" way a few pixels
(calculate the vector vx/vy with the specified length and the direction
away from the "via" node along the first segment of the "from" way)
*/
double distanceFromVia=14;
double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x);
double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y);
double fromAngle;
if(dx == 0.0) {
fromAngle = Math.PI/2;
} else {
fromAngle = Math.atan(dy / dx);
}
double fromAngleDeg = Math.toDegrees(fromAngle);
double vx = distanceFromVia * Math.cos(fromAngle);
double vy = distanceFromVia * Math.sin(fromAngle);
if(pFrom.x < pVia.x) {
vx = -vx;
}
if(pFrom.y < pVia.y) {
vy = -vy;
}
//if(restrictionDebug)
// System.out.println("vx " + vx + " vy " + vy);
/* go a few pixels away from the way (in a right angle)
(calculate the vx2/vy2 vector with the specified length and the direction
90degrees away from the first segment of the "from" way)
*/
double distanceFromWay=10;
double vx2 = 0;
double vy2 = 0;
double iconAngle = 0;
if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
}
iconAngle = 270+fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
}
iconAngle = 90-fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
}
iconAngle = 90+fromAngleDeg;
}
if(pFrom.x >= pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
}
iconAngle = 270-fromAngleDeg;
}
IconElemStyle nodeStyle = getPrimitiveNodeStyle(r);
if (nodeStyle == null) {
putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true);
return;
}
/* rotate icon with direction last node in from to */
//if(restrictionDebug)
// System.out.println("Deg1 " + fromAngleDeg + " Deg2 " + (fromAngleDeg + 180) + " Icon " + iconAngle);
ImageIcon rotatedIcon = ImageProvider.createRotatedImage(null /*icon2*/, nodeStyle.icon, iconAngle);
/* scale down icon to 16*16 pixels */
ImageIcon smallIcon = new ImageIcon(rotatedIcon.getImage().getScaledInstance(16 , 16, Image.SCALE_SMOOTH));
int w = smallIcon.getIconWidth(), h=smallIcon.getIconHeight();
smallIcon.paintIcon ( Main.map.mapView, g, (int)(pVia.x+vx+vx2)-w/2, (int)(pVia.y+vy+vy2)-h/2 );
if (data.isSelected(r))
{
g.setColor ( selectedColor );
g.drawRect ((int)(pVia.x+vx+vx2)-w/2-2,(int)(pVia.y+vy+vy2)-h/2-2, w+4, h+4);
}
}
class PolyData {
public Polygon poly = new Polygon();
public Way way;
public boolean selected = false;
private Point p = null;
private Collection<Polygon> inner = null;
PolyData(Way w)
{
way = w;
for (Node n : w.getNodes())
{
p = nc.getPoint(n);
poly.addPoint(p.x,p.y);
}
}
public int contains(Polygon p)
{
int contains = p.npoints;
for(int i = 0; i < p.npoints; ++i)
{
if(poly.contains(p.xpoints[i],p.ypoints[i])) {
--contains;
}
}
if(contains == 0) return 1;
if(contains == p.npoints) return 0;
return 2;
}
public void addInner(Polygon p)
{
if(inner == null) {
inner = new ArrayList<Polygon>();
}
inner.add(p);
}
public boolean isClosed()
{
return (poly.npoints >= 3
&& poly.xpoints[0] == poly.xpoints[poly.npoints-1]
&& poly.ypoints[0] == poly.ypoints[poly.npoints-1]);
}
public Polygon get()
{
if(inner != null)
{
for (Polygon pp : inner)
{
for(int i = 0; i < pp.npoints; ++i) {
poly.addPoint(pp.xpoints[i],pp.ypoints[i]);
}
poly.addPoint(p.x,p.y);
}
inner = null;
}
return poly;
}
}
void addInnerToOuters(Relation r, boolean incomplete, PolyData pdInner, LinkedList<PolyData> outerPolygons)
{
Way wInner = pdInner.way;
if(wInner != null && !wInner.isClosed())
{
Point pInner = nc.getPoint(wInner.getNode(0));
pdInner.poly.addPoint(pInner.x,pInner.y);
}
PolyData o = null;
for (PolyData pdOuter : outerPolygons)
{
Integer c = pdOuter.contains(pdInner.poly);
if(c >= 1)
{
if(c > 1 && pdOuter.way != null && pdOuter.way.isClosed())
{
putError(r, tr("Intersection between ways ''{0}'' and ''{1}''.",
pdOuter.way.getDisplayName(DefaultNameFormatter.getInstance()), wInner.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
if(o == null || o.contains(pdOuter.poly) > 0) {
o = pdOuter;
}
}
}
if(o == null)
{
if(!incomplete)
{
putError(r, tr("Inner way ''{0}'' is outside.",
wInner.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
o = outerPolygons.get(0);
}
o.addInner(pdInner.poly);
}
public boolean drawMultipolygon(Relation r) {
Collection<Way> inner = new LinkedList<Way>();
Collection<Way> outer = new LinkedList<Way>();
Collection<Way> innerclosed = new LinkedList<Way>();
Collection<Way> outerclosed = new LinkedList<Way>();
boolean incomplete = false;
boolean drawn = false;
for (RelationMember m : r.getMembers())
{
if (m.getMember().isDeleted()) {
putError(r, tr("Deleted member ''{0}'' in relation.",
m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
} else if(m.getMember().incomplete) {
incomplete = true;
} else {
if(m.isWay()) {
Way w = m.getWay();
if(w.getNodesCount() < 2) {
putError(r, tr("Way ''{0}'' with less than two points.",
w.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
else if("inner".equals(m.getRole())) {
inner.add(w);
} else if("outer".equals(m.getRole())) {
outer.add(w);
} else {
putError(r, tr("No useful role ''{0}'' for Way ''{1}''.",
m.getRole(), w.getDisplayName(DefaultNameFormatter.getInstance())), true);
if(!m.hasRole()) {
outer.add(w);
} else if(data.isSelected(r)) {
drawSelectedMember(m.getMember(), styles != null
? getPrimitiveStyle(m.getMember()) : null, true, true);
}
}
}
else
{
putError(r, tr("Non-Way ''{0}'' in multipolygon.",
m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
}
}
}
ElemStyle wayStyle = styles != null ? getPrimitiveStyle(r) : null;
if(styles != null && (wayStyle == null || !(wayStyle instanceof AreaElemStyle)))
{
for (Way w : outer)
{
if(wayStyle == null) {
wayStyle = styles.getArea(w);
}
}
r.mappaintStyle = wayStyle;
}
if(wayStyle != null && wayStyle instanceof AreaElemStyle)
{
boolean zoomok = isZoomOk(wayStyle);
boolean visible = false;
Collection<Way> outerjoin = new LinkedList<Way>();
Collection<Way> innerjoin = new LinkedList<Way>();
drawn = true;
for (Way w : outer)
{
if(w.isClosed()) {
outerclosed.add(w);
} else {
outerjoin.add(w);
}
}
for (Way w : inner)
{
if(w.isClosed()) {
innerclosed.add(w);
} else {
innerjoin.add(w);
}
}
if(outerclosed.size() == 0 && outerjoin.size() == 0)
{
putError(r, tr("No outer way for multipolygon ''{0}''.",
r.getDisplayName(DefaultNameFormatter.getInstance())), true);
visible = true; /* prevent killing remaining ways */
}
else if(zoomok)
{
LinkedList<PolyData> outerPoly = new LinkedList<PolyData>();
for (Way w : outerclosed) {
outerPoly.add(new PolyData(w));
}
outerPoly.addAll(joinWays(outerjoin, incomplete ? null : r));
for (Way wInner : innerclosed)
{
PolyData pdInner = new PolyData(wInner);
// incomplete is probably redundant
addInnerToOuters(r, incomplete, pdInner, outerPoly);
}
for (PolyData pdInner : joinWays(innerjoin, incomplete ? null : r)) {
addInnerToOuters(r, incomplete, pdInner, outerPoly);
}
AreaElemStyle areaStyle = (AreaElemStyle)wayStyle;
for (PolyData pd : outerPoly) {
Polygon p = pd.get();
if(!isPolygonVisible(p)) {
continue;
}
boolean selected = pd.selected || data.isSelected(pd.way) || data.isSelected(r);
drawAreaPolygon(p, selected ? selectedColor : areaStyle.color);
visible = true;
}
}
if(!visible)
return drawn;
for (Way wInner : inner)
{
ElemStyle innerStyle = getPrimitiveStyle(wInner);
if(innerStyle == null)
{
if (data.isSelected(wInner)) {
continue;
}
if(zoomok && (wInner.mappaintDrawnCode != paintid
|| outer.size() == 0))
{
drawWay(wInner, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color, data.isSelected(wInner)
|| data.isSelected(r));
}
wInner.mappaintDrawnCode = paintid;
}
else
{
if(data.isSelected(r))
{
drawSelectedMember(wInner, innerStyle,
!wayStyle.equals(innerStyle), data.isSelected(wInner));
}
if(wayStyle.equals(innerStyle))
{
putError(r, tr("Style for inner way ''{0}'' equals multipolygon.",
wInner.getDisplayName(DefaultNameFormatter.getInstance())), false);
if(!data.isSelected(r)) {
wInner.mappaintDrawnAreaCode = paintid;
}
}
}
}
for (Way wOuter : outer)
{
ElemStyle outerStyle = getPrimitiveStyle(wOuter);
if(outerStyle == null)
{
// Selected ways are drawn at the very end
if (data.isSelected(wOuter)) {
continue;
}
if(zoomok)
{
drawWay(wOuter, ((AreaElemStyle)wayStyle).line,
((AreaElemStyle)wayStyle).color, data.isSelected(wOuter)
|| data.isSelected(r));
}
wOuter.mappaintDrawnCode = paintid;
}
else
{
if(outerStyle instanceof AreaElemStyle
&& !wayStyle.equals(outerStyle))
{
putError(r, tr("Style for outer way ''{0}'' mismatches.",
wOuter.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
if(data.isSelected(r))
{
drawSelectedMember(wOuter, outerStyle, false, false);
}
else if(outerStyle instanceof AreaElemStyle) {
wOuter.mappaintDrawnAreaCode = paintid;
}
}
}
}
return drawn;
}
protected Polygon getPolygon(Way w)
{
Polygon polygon = new Polygon();
for (Node n : w.getNodes())
{
Point p = nc.getPoint(n);
polygon.addPoint(p.x,p.y);
}
return polygon;
}
protected Point2D getCentroid(Polygon p)
{
double cx = 0.0, cy = 0.0, a = 0.0;
// usually requires points[0] == points[npoints] and can then use i+1 instead of j.
// Faked it slowly using j. If this is really gets used, this should be fixed.
for (int i = 0; i < p.npoints; i++) {
int j = i+1 == p.npoints ? 0 : i+1;
a += (p.xpoints[i] * p.ypoints[j]) - (p.ypoints[i] * p.xpoints[j]);
cx += (p.xpoints[i] + p.xpoints[j]) * (p.xpoints[i] * p.ypoints[j] - p.ypoints[i] * p.xpoints[j]);
cy += (p.ypoints[i] + p.ypoints[j]) * (p.xpoints[i] * p.ypoints[j] - p.ypoints[i] * p.xpoints[j]);
}
return new Point2D.Double(cx / (3.0*a), cy / (3.0*a));
}
protected double getArea(Polygon p)
{
double sum = 0.0;
// usually requires points[0] == points[npoints] and can then use i+1 instead of j.
// Faked it slowly using j. If this is really gets used, this should be fixed.
for (int i = 0; i < p.npoints; i++) {
int j = i+1 == p.npoints ? 0 : i+1;
sum = sum + (p.xpoints[i] * p.ypoints[j]) - (p.ypoints[i] * p.xpoints[j]);
}
return Math.abs(sum/2.0);
}
protected void drawArea(Way w, Color color)
{
Polygon polygon = getPolygon(w);
/* set the opacity (alpha) level of the filled polygon */
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), fillAlpha));
g.fillPolygon(polygon);
if (showNames > dist) {
String name = getWayName(w);
if (name!=null /* && annotate */) {
Rectangle pb = polygon.getBounds();
FontMetrics fontMetrics = g.getFontMetrics(orderFont); // if slow, use cache
Rectangle2D nb = fontMetrics.getStringBounds(name, g); // if slow, approximate by strlen()*maxcharbounds(font)
// Point2D c = getCentroid(polygon);
// Using the Centroid is Nicer for buildings like: +--------+
// but this needs to be fast. As most houses are | 42 |
// boxes anyway, the center of the bounding box +---++---+
// will have to do. ++
// Centroids are not optimal either, just imagine a U-shaped house.
// Point2D c = new Point2D.Double(pb.x + pb.width / 2.0, pb.y + pb.height / 2.0);
// Rectangle2D.Double centeredNBounds =
// new Rectangle2D.Double(c.getX() - nb.getWidth()/2,
// c.getY() - nb.getHeight()/2,
// nb.getWidth(),
// nb.getHeight());
Rectangle centeredNBounds = new Rectangle(pb.x + (int)((pb.width - nb.getWidth())/2.0),
pb.y + (int)((pb.height - nb.getHeight())/2.0),
(int)nb.getWidth(),
(int)nb.getHeight());
//// Draw name bounding box for debugging:
// g.setColor(new Color(255,255,0,128));
// g.drawRect((int)centeredNBounds.getMinX(),
// (int)centeredNBounds.getMinY(),
// (int)centeredNBounds.getWidth(),
// (int)centeredNBounds.getHeight());
if ((pb.width >= nb.getWidth() && pb.height >= nb.getHeight()) && // quick check
polygon.contains(centeredNBounds) // slow but nice
) {
g.setColor(areaTextColor);
Font defaultFont = g.getFont();
g.setFont (orderFont);
g.drawString (name,
(int)(centeredNBounds.getMinX() - nb.getMinX()),
(int)(centeredNBounds.getMinY() - nb.getMinY()));
g.setFont(defaultFont);
}
}
}
}
protected String getWayName(Way w) {
String name = null;
if (w.hasKeys()) {
for (String rn : regionalNameOrder) {
name = w.get(rn);
if (name != null) {
break;
}
}
}
return name;
}
protected void drawAreaPolygon(Polygon polygon, Color color)
{
/* set the opacity (alpha) level of the filled polygon */
g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), fillAlpha));
g.fillPolygon(polygon);
}
protected void drawNode(Node n, ImageIcon icon, boolean annotate, boolean selected) {
Point p = nc.getPoint(n);
if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth()) || (p.y > nc.getHeight())) return;
//profilerVisibleNodes++;
int w = icon.getIconWidth(), h=icon.getIconHeight();
icon.paintIcon ( Main.map.mapView, g, p.x-w/2, p.y-h/2 );
if(showNames > dist)
{
String name = getNodeName(n);
if (name!=null && annotate)
{
if (inactive || n.isDisabled()) {
g.setColor(inactiveColor);
} else {
g.setColor(textColor);
}
Font defaultFont = g.getFont();
g.setFont (orderFont);
g.drawString (name, p.x+w/2+2, p.y+h/2+2);
g.setFont(defaultFont);
}
}
if (selected)
{
g.setColor ( selectedColor );
g.drawRect (p.x-w/2-2, p.y-h/2-2, w+4, h+4);
}
}
protected String getNodeName(Node n) {
String name = null;
if (n.hasKeys()) {
for (String rn : regionalNameOrder) {
name = n.get(rn);
if (name != null) {
break;
}
}
}
return name;
}
private void drawSeg(Node n1, Node n2, Color col, boolean showDirection, int width, float dashed[], Color dashedColor) {
//profilerSegments++;
if (col != currentColor || width != currentWidth || !Arrays.equals(dashed,currentDashed) || dashedColor != currentDashedColor) {
displaySegments(col, width, dashed, dashedColor);
}
Point p1 = nc.getPoint(n1);
Point p2 = nc.getPoint(n2);
if (!isSegmentVisible(p1, p2))
return;
//profilerVisibleSegments++;
currentPath.moveTo(p1.x, p1.y);
currentPath.lineTo(p2.x, p2.y);
if (showDirection) {
double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
currentPath.lineTo((int)(p2.x + 10*Math.cos(t-PHI)), (int)(p2.y + 10*Math.sin(t-PHI)));
currentPath.moveTo((int)(p2.x + 10*Math.cos(t+PHI)), (int)(p2.y + 10*Math.sin(t+PHI)));
currentPath.lineTo(p2.x, p2.y);
}
}
@Override
protected void displaySegments() {
displaySegments(null, 0, new float[0], null);
}
protected void displaySegments(Color newColor, int newWidth, float newDash[], Color newDashedColor) {
if (currentPath != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(inactive ? inactiveColor : currentColor);
if (currentStroke == null && useStrokes > dist) {
if (currentDashed.length > 0) {
try {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_BUTT,BasicStroke.JOIN_ROUND,0,currentDashed,0));
} catch (IllegalArgumentException e) {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
}
} else {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
}
}
g2d.draw(currentPath);
if(currentDashedColor != null) {
g2d.setColor(currentDashedColor);
if (currentStroke == null && useStrokes > dist) {
if (currentDashed.length > 0) {
float[] currentDashedOffset = new float[currentDashed.length];
System.arraycopy(currentDashed, 1, currentDashedOffset, 0, currentDashed.length - 1);
currentDashedOffset[currentDashed.length-1] = currentDashed[0];
float offset = currentDashedOffset[0];
try {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_BUTT,BasicStroke.JOIN_ROUND,0,currentDashedOffset,offset));
} catch (IllegalArgumentException e) {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
}
} else {
g2d.setStroke(new BasicStroke(currentWidth,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
}
}
g2d.draw(currentPath);
}
if(useStrokes > dist) {
g2d.setStroke(new BasicStroke(1));
}
currentPath = new GeneralPath();
currentColor = newColor;
currentWidth = newWidth;
currentDashed = newDash;
currentDashedColor = newDashedColor;
currentStroke = null;
}
}
/**
* Draw the node as small rectangle with the given color.
*
* @param n The node to draw.
* @param color The color of the node.
*/
@Override
public void drawNode(Node n, Color color, int size, int radius, boolean fill) {
if (isZoomOk(null) && size > 1) {
Point p = nc.getPoint(n);
if ((p.x < 0) || (p.y < 0) || (p.x > nc.getWidth())
|| (p.y > nc.getHeight()))
return;
//profilerVisibleNodes++;
if (inactive || n.isDisabled()) {
g.setColor(inactiveColor);
} else {
g.setColor(color);
}
if (fill) {
g.fillRect(p.x - radius, p.y - radius, size, size);
g.drawRect(p.x - radius, p.y - radius, size, size);
} else {
g.drawRect(p.x - radius, p.y - radius, size, size);
}
if(showNames > dist)
{
String name = getNodeName(n);
if (name!=null /* && annotate */)
{
if (inactive || n.isDisabled()) {
g.setColor(inactiveColor);
} else {
g.setColor(textColor);
}
Font defaultFont = g.getFont();
g.setFont (orderFont);
g.drawString (name, p.x+radius+2, p.y+radius+2);
g.setFont(defaultFont);
}
}
}
}
boolean drawable(OsmPrimitive osm)
{
return !osm.isDeleted() && !osm.isFiltered() && !osm.incomplete;
}
@Override
public void getColors()
{
super.getColors();
untaggedColor = Main.pref.getColor(marktr("untagged"),Color.GRAY);
textColor = Main.pref.getColor (marktr("text"), Color.WHITE);
areaTextColor = Main.pref.getColor (marktr("areatext"), Color.LIGHT_GRAY);
}
DataSet data;
<T extends OsmPrimitive> Collection<T> selectedLast(final DataSet data, Collection <T> prims) {
ArrayList<T> sorted = new ArrayList<T>(prims);
Collections.sort(sorted,
new Comparator<T>() {
public int compare(T o1, T o2) {
boolean s1 = data.isSelected(o1);
boolean s2 = data.isSelected(o2);
if (s1 && !s2)
return 1;
if (!s1 && s2)
return -1;
return o1.compareTo(o2);
}
});
return sorted;
}
/* Shows areas before non-areas */
@Override
public void visitAll(DataSet data, boolean virtual, Bounds bounds) {
BBox bbox = new BBox(bounds);
this.data = data;
//boolean profiler = Main.pref.getBoolean("mappaint.profiler",false);
//profilerOmitDraw = Main.pref.getBoolean("mappaint.profiler.omitdraw",false);
useStyleCache = Main.pref.getBoolean("mappaint.cache", true);
int fillAreas = Main.pref.getInteger("mappaint.fillareas", 10000000);
fillAlpha = Math.min(255, Math.max(0, Integer.valueOf(Main.pref.getInteger("mappaint.fillalpha", 50))));
showNames = Main.pref.getInteger("mappaint.shownames", 10000000);
showIcons = Main.pref.getInteger("mappaint.showicons", 10000000);
useStrokes = Main.pref.getInteger("mappaint.strokes", 10000000);
LatLon ll1 = nc.getLatLon(0, 0);
LatLon ll2 = nc.getLatLon(100, 0);
dist = ll1.greatCircleDistance(ll2);
//long profilerStart = java.lang.System.currentTimeMillis();
//long profilerLast = profilerStart;
//int profilerN;
//if(profiler)
// System.out.println("Mappaint Profiler (" +
// (useStyleCache ? "cache=true, " : "cache=false, ") +
// "fillareas " + fillAreas + ", " +
// "fillalpha=" + fillAlpha + "%, " +
// "dist=" + (int)dist + "m)");
getSettings(virtual);
useRealWidth = Main.pref.getBoolean("mappaint.useRealWidth", false);
zoomLevelDisplay = Main.pref.getBoolean("mappaint.zoomLevelDisplay", false);
circum = Main.map.mapView.getDist100Pixel();
styles = MapPaintStyles.getStyles().getStyleSet();
drawMultipolygon = Main.pref.getBoolean("mappaint.multipolygon", true);
drawRestriction = Main.pref.getBoolean("mappaint.restriction", true);
//restrictionDebug = Main.pref.getBoolean("mappaint.restriction.debug",false);
leftHandTraffic = Main.pref.getBoolean("mappaint.lefthandtraffic", false);
orderFont = new Font(Main.pref.get("mappaint.font", "Helvetica"), Font.PLAIN, Main.pref.getInteger("mappaint.fontsize", 8));
String[] names = {"name:" + LanguageInfo.getJOSMLocaleCode(), "name", "int_name", "ref", "operator", "brand", "addr:housenumber"};
regionalNameOrder = Main.pref.getCollection("mappaint.nameOrder", Arrays.asList(names));
minEN = nc.getEastNorth(0, nc.getHeight() - 1);
maxEN = nc.getEastNorth(nc.getWidth() - 1, 0);
data.clearErrors();
++paintid;
//profilerVisibleNodes = 0;
//profilerVisibleWays = 0;
//profilerVisibleAreas = 0;
//profilerSegments = 0;
//profilerVisibleSegments = 0;
//if(profiler)
//{
// System.out.format("Prepare : %5dms\n", (java.lang.System.currentTimeMillis()-profilerLast));
// profilerLast = java.lang.System.currentTimeMillis();
//}
if (fillAreas > dist && styles != null && styles.hasAreas()) {
Collection<Way> noAreaWays = new LinkedList<Way>();
/*** RELATIONS ***/
// profilerN = 0;
for (final Relation osm: data.getRelations()) {
if (drawable(osm)) {
paintUnselectedRelation(osm);
// profilerN++;
}
}
// if(profiler)
// {
// System.out.format("Relations: %5dms, calls=%7d\n", (java.lang.System.currentTimeMillis()-profilerLast), profilerN);
// profilerLast = java.lang.System.currentTimeMillis();
// }
/*** AREAS ***/
// profilerN = 0;
for (final Way osm : selectedLast(data, data.searchWays(bbox))) {
if (drawable(osm) && osm.mappaintDrawnCode != paintid) {
if (isPrimitiveArea(osm) && osm.mappaintDrawnAreaCode != paintid) {
drawWay(osm, fillAreas);
// profilerN++;
}// else {
noAreaWays.add(osm);
//}
}
}
// if(profiler)
// {
// System.out.format("Areas : %5dms, calls=%7d, visible=%d\n",
// (java.lang.System.currentTimeMillis()-profilerLast), profilerN, profilerVisibleAreas);
// profilerLast = java.lang.System.currentTimeMillis();
// }
/*** WAYS ***/
// profilerN = 0;
for (final Way osm : noAreaWays) {
drawWay(osm, 0);
// profilerN++;
}
// if(profiler)
// {
// System.out.format("Ways : %5dms, calls=%7d, visible=%d\n",
// (java.lang.System.currentTimeMillis()-profilerLast), profilerN, profilerVisibleWays);
// profilerLast = java.lang.System.currentTimeMillis();
// }
} else {
/*** WAYS (filling disabled) ***/
// profilerN = 0;
for (final Way way: data.getWays()) {
if (drawable(way) && !data.isSelected(way)) {
drawWay(way, 0);
// profilerN++;
}
}
// if(profiler)
// {
// System.out.format("Ways : %5dms, calls=%7d, visible=%d\n",
// (java.lang.System.currentTimeMillis()-profilerLast), profilerN, profilerVisibleWays);
// profilerLast = java.lang.System.currentTimeMillis();
// }
}
/*** SELECTED ***/
//profilerN = 0;
for (final OsmPrimitive osm : data.getSelected()) {
if (!osm.incomplete && !osm.isDeleted() && !(osm instanceof Node)
&& osm.mappaintDrawnCode != paintid
) {
osm.visit(new AbstractVisitor() {
public void visit(Way w) {
drawWay(w, 0);
}
public void visit(Node n) {
drawNode(n);
}
public void visit(Relation r) {
/* TODO: is it possible to do this like the nodes/ways code? */
//if(profilerOmitDraw)
// return;
for (RelationMember m : r.getMembers()) {
if (m.isNode() && drawable(m.getMember())) {
drawSelectedMember(m.getMember(), styles != null ? getPrimitiveStyle(m.getMember()) : null, true, true);
}
}
}
});
// profilerN++;
}
}
//if(profiler)
//{
// System.out.format("Selected : %5dms, calls=%7d\n", (java.lang.System.currentTimeMillis()-profilerLast), profilerN);
// profilerLast = java.lang.System.currentTimeMillis();
//}
/*** DISPLAY CACHED SEGMENTS (WAYS) NOW ***/
displaySegments();
/*** NODES ***/
//profilerN = 0;
for (final Node osm: data.searchNodes(bbox)) {
if (!osm.incomplete && !osm.isDeleted() && (data.isSelected(osm) || !osm.isFiltered())
&& osm.mappaintDrawnCode != paintid)
{
drawNode(osm);
// profilerN++;
}
}
//if(profiler)
//{
// System.out.format("Nodes : %5dms, calls=%7d, visible=%d\n",
// (java.lang.System.currentTimeMillis()-profilerLast), profilerN, profilerVisibleNodes);
// profilerLast = java.lang.System.currentTimeMillis();
//}
/*** VIRTUAL ***/
if (virtualNodeSize != 0) {
// profilerN = 0;
currentColor = nodeColor;
for (final OsmPrimitive osm: data.searchWays(bbox)) {
if (osm.isUsable() && !osm.isFiltered())
{
/* TODO: move this into the SimplePaint code? */
// if(!profilerOmitDraw)
visitVirtual((Way)osm);
// profilerN++;
}
}
// if(profiler)
// {
// System.out.format("Virtual : %5dms, calls=%7d\n", (java.lang.System.currentTimeMillis()-profilerLast), profilerN);
// profilerLast = java.lang.System.currentTimeMillis();
// }
displaySegments(null);
}
//if(profiler)
//{
// System.out.format("Segments : calls=%7d, visible=%d\n", profilerSegments, profilerVisibleSegments);
// System.out.format("All : %5dms\n", (profilerLast-profilerStart));
//}
}
/**
* Draw a number of the order of the two consecutive nodes within the
* parents way
*/
protected void drawOrderNumber(Node n1, Node n2, int orderNumber) {
Point p1 = nc.getPoint(n1);
Point p2 = nc.getPoint(n2);
drawOrderNumber(p1, p2, orderNumber);
}
public void putError(OsmPrimitive p, String text, boolean isError)
{
data.addError(p, isError ? tr("Error: {0}", text) : tr("Warning: {0}", text));
}
}
| false | true | public void drawRestriction(Relation r) {
//if(restrictionDebug)
// System.out.println("Restriction: " + r.keys.get("name") + " restriction " + r.keys.get("restriction"));
Way fromWay = null;
Way toWay = null;
OsmPrimitive via = null;
/* find the "from", "via" and "to" elements */
for (RelationMember m : r.getMembers())
{
//if(restrictionDebug)
// System.out.println("member " + m.member + " selected " + r.selected);
if (m.getMember().isDeleted()) {
putError(r, tr("Deleted member ''{0}'' in relation.",
m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
} else if(m.getMember().incomplete)
return;
else
{
if(m.isWay())
{
Way w = m.getWay();
if(w.getNodesCount() < 2)
{
putError(r, tr("Way ''{0}'' with less than two points.",
w.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
else if("from".equals(m.getRole())) {
if(fromWay != null) {
putError(r, tr("More than one \"from\" way found."), true);
} else {
fromWay = w;
}
} else if("to".equals(m.getRole())) {
if(toWay != null) {
putError(r, tr("More than one \"to\" way found."), true);
} else {
toWay = w;
}
} else if("via".equals(m.getRole())) {
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = w;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
}
else if(m.isNode())
{
Node n = m.getNode();
if("via".equals(m.getRole()))
{
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = n;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
} else {
putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
}
}
}
if (fromWay == null) {
putError(r, tr("No \"from\" way found."), true);
return;
}
if (toWay == null) {
putError(r, tr("No \"to\" way found."), true);
return;
}
if (via == null) {
putError(r, tr("No \"via\" node or way found."), true);
return;
}
Node viaNode;
if(via instanceof Node)
{
viaNode = (Node) via;
if(!fromWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"from\" way doesn't start or end at a \"via\" node."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"to\" way doesn't start or end at a \"via\" node."), true);
}
}
else
{
Way viaWay = (Way) via;
Node firstNode = viaWay.firstNode();
Node lastNode = viaWay.lastNode();
boolean onewayvia = false;
String onewayviastr = viaWay.get("oneway");
if(onewayviastr != null)
{
if("-1".equals(onewayviastr)) {
onewayvia = true;
firstNode = lastNode;
lastNode = firstNode;
} else {
onewayvia = OsmUtils.getOsmBoolean(onewayviastr);
}
}
if(fromWay.isFirstLastNode(firstNode)) {
viaNode = firstNode;
} else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
viaNode = lastNode;
} else {
putError(r, tr("The \"from\" way doesn't start or end at the \"via\" way."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) {
putError(r, tr("The \"to\" way doesn't start or end at the \"via\" way."), true);
}
}
/* find the "direct" nodes before the via node */
Node fromNode = null;
if(fromWay.firstNode() == via) {
//System.out.println("From way heading away from via");
fromNode = fromWay.getNode(1);
} else {
//System.out.println("From way heading towards via");
fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
}
Point pFrom = nc.getPoint(fromNode);
Point pVia = nc.getPoint(viaNode);
//if(restrictionDebug) {
/* find the "direct" node after the via node */
// Node toNode = null;
// if(toWay.firstNode() == via) {
// System.out.println("To way heading away from via");
// toNode = toWay.nodes.get(1);
// } else {
// System.out.println("To way heading towards via");
// toNode = toWay.nodes.get(toWay.nodes.size()-2);
// }
// Point pTo = nc.getPoint(toNode);
// /* debug output of interesting nodes */
// System.out.println("From: " + fromNode);
// drawNode(fromNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("Via: " + via);
// drawNode(via, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("To: " + toNode);
// drawNode(toNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("From X: " + pFrom.x + " Y " + pFrom.y);
// System.out.println("Via X: " + pVia.x + " Y " + pVia.y);
// System.out.println("To X: " + pTo.x + " Y " + pTo.y);
//}
/* starting from via, go back the "from" way a few pixels
(calculate the vector vx/vy with the specified length and the direction
away from the "via" node along the first segment of the "from" way)
*/
double distanceFromVia=14;
double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x);
double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y);
double fromAngle;
if(dx == 0.0) {
fromAngle = Math.PI/2;
} else {
fromAngle = Math.atan(dy / dx);
}
double fromAngleDeg = Math.toDegrees(fromAngle);
double vx = distanceFromVia * Math.cos(fromAngle);
double vy = distanceFromVia * Math.sin(fromAngle);
if(pFrom.x < pVia.x) {
vx = -vx;
}
if(pFrom.y < pVia.y) {
vy = -vy;
}
//if(restrictionDebug)
// System.out.println("vx " + vx + " vy " + vy);
/* go a few pixels away from the way (in a right angle)
(calculate the vx2/vy2 vector with the specified length and the direction
90degrees away from the first segment of the "from" way)
*/
double distanceFromWay=10;
double vx2 = 0;
double vy2 = 0;
double iconAngle = 0;
if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
}
iconAngle = 270+fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
}
iconAngle = 90-fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
}
iconAngle = 90+fromAngleDeg;
}
if(pFrom.x >= pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
}
iconAngle = 270-fromAngleDeg;
}
IconElemStyle nodeStyle = getPrimitiveNodeStyle(r);
if (nodeStyle == null) {
putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true);
return;
}
/* rotate icon with direction last node in from to */
//if(restrictionDebug)
// System.out.println("Deg1 " + fromAngleDeg + " Deg2 " + (fromAngleDeg + 180) + " Icon " + iconAngle);
ImageIcon rotatedIcon = ImageProvider.createRotatedImage(null /*icon2*/, nodeStyle.icon, iconAngle);
/* scale down icon to 16*16 pixels */
ImageIcon smallIcon = new ImageIcon(rotatedIcon.getImage().getScaledInstance(16 , 16, Image.SCALE_SMOOTH));
int w = smallIcon.getIconWidth(), h=smallIcon.getIconHeight();
smallIcon.paintIcon ( Main.map.mapView, g, (int)(pVia.x+vx+vx2)-w/2, (int)(pVia.y+vy+vy2)-h/2 );
if (data.isSelected(r))
{
g.setColor ( selectedColor );
g.drawRect ((int)(pVia.x+vx+vx2)-w/2-2,(int)(pVia.y+vy+vy2)-h/2-2, w+4, h+4);
}
}
| public void drawRestriction(Relation r) {
//if(restrictionDebug)
// System.out.println("Restriction: " + r.keys.get("name") + " restriction " + r.keys.get("restriction"));
Way fromWay = null;
Way toWay = null;
OsmPrimitive via = null;
/* find the "from", "via" and "to" elements */
for (RelationMember m : r.getMembers())
{
//if(restrictionDebug)
// System.out.println("member " + m.member + " selected " + r.selected);
if (m.getMember().isDeleted()) {
putError(r, tr("Deleted member ''{0}'' in relation.",
m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
} else if(m.getMember().incomplete)
return;
else
{
if(m.isWay())
{
Way w = m.getWay();
if(w.getNodesCount() < 2)
{
putError(r, tr("Way ''{0}'' with less than two points.",
w.getDisplayName(DefaultNameFormatter.getInstance())), true);
}
else if("from".equals(m.getRole())) {
if(fromWay != null) {
putError(r, tr("More than one \"from\" way found."), true);
} else {
fromWay = w;
}
} else if("to".equals(m.getRole())) {
if(toWay != null) {
putError(r, tr("More than one \"to\" way found."), true);
} else {
toWay = w;
}
} else if("via".equals(m.getRole())) {
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = w;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
}
else if(m.isNode())
{
Node n = m.getNode();
if("via".equals(m.getRole()))
{
if(via != null) {
putError(r, tr("More than one \"via\" found."), true);
} else {
via = n;
}
} else {
putError(r, tr("Unknown role ''{0}''.", m.getRole()), true);
}
} else {
putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true);
}
}
}
if (fromWay == null) {
putError(r, tr("No \"from\" way found."), true);
return;
}
if (toWay == null) {
putError(r, tr("No \"to\" way found."), true);
return;
}
if (via == null) {
putError(r, tr("No \"via\" node or way found."), true);
return;
}
Node viaNode;
if(via instanceof Node)
{
viaNode = (Node) via;
if(!fromWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"from\" way doesn't start or end at a \"via\" node."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode)) {
putError(r, tr("The \"to\" way doesn't start or end at a \"via\" node."), true);
}
}
else
{
Way viaWay = (Way) via;
Node firstNode = viaWay.firstNode();
Node lastNode = viaWay.lastNode();
boolean onewayvia = false;
String onewayviastr = viaWay.get("oneway");
if(onewayviastr != null)
{
if("-1".equals(onewayviastr)) {
onewayvia = true;
Node tmp = firstNode;
firstNode = lastNode;
lastNode = tmp;
} else {
onewayvia = OsmUtils.getOsmBoolean(onewayviastr);
}
}
if(fromWay.isFirstLastNode(firstNode)) {
viaNode = firstNode;
} else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) {
viaNode = lastNode;
} else {
putError(r, tr("The \"from\" way doesn't start or end at the \"via\" way."), true);
return;
}
if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) {
putError(r, tr("The \"to\" way doesn't start or end at the \"via\" way."), true);
}
}
/* find the "direct" nodes before the via node */
Node fromNode = null;
if(fromWay.firstNode() == via) {
//System.out.println("From way heading away from via");
fromNode = fromWay.getNode(1);
} else {
//System.out.println("From way heading towards via");
fromNode = fromWay.getNode(fromWay.getNodesCount()-2);
}
Point pFrom = nc.getPoint(fromNode);
Point pVia = nc.getPoint(viaNode);
//if(restrictionDebug) {
/* find the "direct" node after the via node */
// Node toNode = null;
// if(toWay.firstNode() == via) {
// System.out.println("To way heading away from via");
// toNode = toWay.nodes.get(1);
// } else {
// System.out.println("To way heading towards via");
// toNode = toWay.nodes.get(toWay.nodes.size()-2);
// }
// Point pTo = nc.getPoint(toNode);
// /* debug output of interesting nodes */
// System.out.println("From: " + fromNode);
// drawNode(fromNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("Via: " + via);
// drawNode(via, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("To: " + toNode);
// drawNode(toNode, selectedColor, selectedNodeSize, selectedNodeRadius, fillSelectedNode);
// System.out.println("From X: " + pFrom.x + " Y " + pFrom.y);
// System.out.println("Via X: " + pVia.x + " Y " + pVia.y);
// System.out.println("To X: " + pTo.x + " Y " + pTo.y);
//}
/* starting from via, go back the "from" way a few pixels
(calculate the vector vx/vy with the specified length and the direction
away from the "via" node along the first segment of the "from" way)
*/
double distanceFromVia=14;
double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x);
double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y);
double fromAngle;
if(dx == 0.0) {
fromAngle = Math.PI/2;
} else {
fromAngle = Math.atan(dy / dx);
}
double fromAngleDeg = Math.toDegrees(fromAngle);
double vx = distanceFromVia * Math.cos(fromAngle);
double vy = distanceFromVia * Math.sin(fromAngle);
if(pFrom.x < pVia.x) {
vx = -vx;
}
if(pFrom.y < pVia.y) {
vy = -vy;
}
//if(restrictionDebug)
// System.out.println("vx " + vx + " vy " + vy);
/* go a few pixels away from the way (in a right angle)
(calculate the vx2/vy2 vector with the specified length and the direction
90degrees away from the first segment of the "from" way)
*/
double distanceFromWay=10;
double vx2 = 0;
double vy2 = 0;
double iconAngle = 0;
if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
}
iconAngle = 270+fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y >= pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
}
iconAngle = 90-fromAngleDeg;
}
if(pFrom.x < pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90));
} else {
vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90));
vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90));
}
iconAngle = 90+fromAngleDeg;
}
if(pFrom.x >= pVia.x && pFrom.y < pVia.y) {
if(!leftHandTraffic) {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180));
} else {
vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg));
vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg));
}
iconAngle = 270-fromAngleDeg;
}
IconElemStyle nodeStyle = getPrimitiveNodeStyle(r);
if (nodeStyle == null) {
putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true);
return;
}
/* rotate icon with direction last node in from to */
//if(restrictionDebug)
// System.out.println("Deg1 " + fromAngleDeg + " Deg2 " + (fromAngleDeg + 180) + " Icon " + iconAngle);
ImageIcon rotatedIcon = ImageProvider.createRotatedImage(null /*icon2*/, nodeStyle.icon, iconAngle);
/* scale down icon to 16*16 pixels */
ImageIcon smallIcon = new ImageIcon(rotatedIcon.getImage().getScaledInstance(16 , 16, Image.SCALE_SMOOTH));
int w = smallIcon.getIconWidth(), h=smallIcon.getIconHeight();
smallIcon.paintIcon ( Main.map.mapView, g, (int)(pVia.x+vx+vx2)-w/2, (int)(pVia.y+vy+vy2)-h/2 );
if (data.isSelected(r))
{
g.setColor ( selectedColor );
g.drawRect ((int)(pVia.x+vx+vx2)-w/2-2,(int)(pVia.y+vy+vy2)-h/2-2, w+4, h+4);
}
}
|
diff --git a/src/main/org/codehaus/groovy/transform/ASTTransformationVisitor.java b/src/main/org/codehaus/groovy/transform/ASTTransformationVisitor.java
index 856dd16fc..8f94d20ed 100644
--- a/src/main/org/codehaus/groovy/transform/ASTTransformationVisitor.java
+++ b/src/main/org/codehaus/groovy/transform/ASTTransformationVisitor.java
@@ -1,266 +1,282 @@
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.transform;
import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.*;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.control.messages.WarningMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
/**
* This class handles the invocation of the ASTAnnotationTransformation
* when it is encountered by a tree walk. One instance of each exists
* for each phase of the compilation it applies to. Before invocation the
* <p/>
* {@link org.codehaus.groovy.transform.ASTTransformationCollectorCodeVisitor} will add a list
* of annotations that this visitor should be concerned about. All other
* annotations are ignored, whether or not they are GroovyASTTransformation
* annotated or not.
* <p/>
* A Two-pass method is used. First all candidate annotations are added to a
* list then the transformations are called on those collected annotations.
* This is done to avoid concurrent modification exceptions during the AST tree
* walk and allows the transformations to alter any portion of the AST tree.
* Hence annotations that are added in this phase will not be processed as
* transformations. They will only be handled in later phases (and then only
* if the type was in the AST prior to any AST transformations being run
* against it).
*
* @author Danno Ferrin (shemnon)
*/
public class ASTTransformationVisitor extends ClassCodeVisitorSupport {
private CompilePhase phase;
private SourceUnit source;
private List<ASTNode[]> targetNodes;
private Map<ASTNode, List<ASTTransformation>> transforms;
private Map<Class<? extends ASTTransformation>, ASTTransformation> transformInstances;
private ASTTransformationVisitor(CompilePhase phase) {
this.phase = phase;
}
protected SourceUnit getSourceUnit() {
return source;
}
/**
* Main loop entry.
* <p/>
* First, it delegates to the super visitClass so we can collect the
* relevant annotations in an AST tree walk.
* <p/>
* Second, it calls the visit method on the transformation for each relevant
* annotation found.
*
* @param classNode the class to visit
*/
public void visitClass(ClassNode classNode) {
// only descend if we have annotations to look for
Map<Class<? extends ASTTransformation>, Set<ASTNode>> baseTransforms = classNode.getTransforms(phase);
if (!baseTransforms.isEmpty()) {
transformInstances = new HashMap<Class<? extends ASTTransformation>, ASTTransformation>();
for (Class<? extends ASTTransformation> transformClass : baseTransforms.keySet()) {
try {
transformInstances.put(transformClass, transformClass.newInstance());
} catch (InstantiationException e) {
source.getErrorCollector().addError(
new SimpleMessage(
"Could not instantiate Transformation Processor " + transformClass
, //+ " declared by " + annotation.getClassNode().getName(),
source));
} catch (IllegalAccessException e) {
source.getErrorCollector().addError(
new SimpleMessage(
"Could not instantiate Transformation Processor " + transformClass
, //+ " declared by " + annotation.getClassNode().getName(),
source));
}
}
// invert the map, is now one to many
transforms = new HashMap<ASTNode, List<ASTTransformation>>();
for (Map.Entry<Class<? extends ASTTransformation>, Set<ASTNode>> entry : baseTransforms.entrySet()) {
for (ASTNode node : entry.getValue()) {
List<ASTTransformation> list = transforms.get(node);
if (list == null) {
list = new ArrayList<ASTTransformation>();
transforms.put(node, list);
}
list.add(transformInstances.get(entry.getKey()));
}
}
targetNodes = new LinkedList<ASTNode[]>();
// fist pass, collect nodes
super.visitClass(classNode);
// second pass, call visit on all of the collected nodes
for (ASTNode[] node : targetNodes) {
for (ASTTransformation snt : transforms.get(node[0])) {
snt.visit(node, source);
}
}
}
}
/**
* Adds the annotation to the internal target list if a match is found.
*
* @param node the node to be processed
*/
public void visitAnnotations(AnnotatedNode node) {
super.visitAnnotations(node);
//noinspection unchecked
for (AnnotationNode annotation : (Collection<AnnotationNode>) node.getAnnotations()) {
if (transforms.containsKey(annotation)) {
targetNodes.add(new ASTNode[]{annotation, node});
}
}
}
public static void addPhaseOperations(CompilationUnit compilationUnit) {
addGlobalTransforms(compilationUnit);
compilationUnit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() {
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(source);
collector.visitClass(classNode);
}
}, Phases.SEMANTIC_ANALYSIS);
for (CompilePhase phase : CompilePhase.values()) {
final ASTTransformationVisitor visitor = new ASTTransformationVisitor(phase);
switch (phase) {
case INITIALIZATION:
case PARSING:
case CONVERSION:
// with transform detection alone these phases are inaccessible, so don't add it
break;
default:
compilationUnit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() {
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
visitor.source = source;
visitor.visitClass(classNode);
}
}, phase.getPhaseNumber());
break;
}
}
}
public static void addGlobalTransforms(CompilationUnit compilationUnit) {
GroovyClassLoader cuLoader = compilationUnit.getClassLoader();
LinkedHashMap<String, URL> globalTransformNames = new LinkedHashMap<String, URL>();
try {
Enumeration<URL> globalServices = cuLoader.getResources("META-INF/services/org.codehaus.groovy.transform.ASTTransformation");
while (globalServices.hasMoreElements()) {
URL service = globalServices.nextElement();
String className;
BufferedReader svcIn = new BufferedReader(new InputStreamReader(service.openStream()));
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
continue;
}
while (className != null) {
if (!className.startsWith("#") && className.length() > 0) {
if (globalTransformNames.containsKey(className)) {
if (!service.equals(globalTransformNames.get(className))) {
compilationUnit.getErrorCollector().addWarning(
WarningMessage.POSSIBLE_ERRORS,
"The global transform for class " + className + " is defined in both "
+ globalTransformNames.get(className).toExternalForm()
+ " and "
+ service.toExternalForm()
+ " - the former definition will be used and the latter ignored.",
null,
null);
}
} else {
globalTransformNames.put(className, service);
}
}
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
//noinspection UnnecessaryContinue
continue;
}
}
}
} catch (IOException e) {
//FIXME the warning message will NPE with what I have :(
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IO Exception attempting to load global transforms:" + e.getMessage(),
null));
}
+ try {
+ Class.forName("java.lang.annotation.Annotation"); // test for 1.5 JVM
+ } catch (Exception e) {
+ // we failed, notify the user
+ StringBuffer sb = new StringBuffer();
+ sb.append("Global ASTTransformations are not enabled in retro builds of groovy.\n");
+ sb.append("The following transformations will be ignored:");
+ for (Map.Entry<String, URL> entry : globalTransformNames.entrySet()) {
+ sb.append('\t');
+ sb.append(entry.getKey());
+ sb.append('\n');
+ }
+ compilationUnit.getErrorCollector().addWarning(new WarningMessage(
+ WarningMessage.POSSIBLE_ERRORS, sb.toString(), null, null));
+ return;
+ }
for (Map.Entry<String, URL> entry : globalTransformNames.entrySet()) {
try {
Class gTransClass = cuLoader.loadClass(entry.getKey());
//noinspection unchecked
GroovyASTTransformation transformAnnotation = (GroovyASTTransformation) gTransClass.getAnnotation(GroovyASTTransformation.class);
if (transformAnnotation == null) {
compilationUnit.getErrorCollector().addWarning(new WarningMessage(
WarningMessage.POSSIBLE_ERRORS,
"Transform Class " + entry.getKey() + " is specified as a global transform in " + entry.getValue().toExternalForm()
+ " but it is not annotated by " + GroovyASTTransformation.class.getName()
+ " the global tranform associated with it may fail and cause the compilation to fail.",
null,
null));
continue;
}
if (ASTTransformation.class.isAssignableFrom(gTransClass)) {
final ASTTransformation instance = (ASTTransformation)gTransClass.newInstance();
compilationUnit.addPhaseOperation(new CompilationUnit.SourceUnitOperation() {
public void call(SourceUnit source) throws CompilationFailedException {
instance.visit(new ASTNode[] {source.getAST()}, source);
}
}, transformAnnotation.phase().getPhaseNumber());
} else {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Transform Class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " is not an ASTTransformation.", null));
}
} catch (Exception e) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Could not instantiate global transform class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " because of exception " + e.toString(), null));
}
}
}
}
| true | true | public static void addGlobalTransforms(CompilationUnit compilationUnit) {
GroovyClassLoader cuLoader = compilationUnit.getClassLoader();
LinkedHashMap<String, URL> globalTransformNames = new LinkedHashMap<String, URL>();
try {
Enumeration<URL> globalServices = cuLoader.getResources("META-INF/services/org.codehaus.groovy.transform.ASTTransformation");
while (globalServices.hasMoreElements()) {
URL service = globalServices.nextElement();
String className;
BufferedReader svcIn = new BufferedReader(new InputStreamReader(service.openStream()));
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
continue;
}
while (className != null) {
if (!className.startsWith("#") && className.length() > 0) {
if (globalTransformNames.containsKey(className)) {
if (!service.equals(globalTransformNames.get(className))) {
compilationUnit.getErrorCollector().addWarning(
WarningMessage.POSSIBLE_ERRORS,
"The global transform for class " + className + " is defined in both "
+ globalTransformNames.get(className).toExternalForm()
+ " and "
+ service.toExternalForm()
+ " - the former definition will be used and the latter ignored.",
null,
null);
}
} else {
globalTransformNames.put(className, service);
}
}
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
//noinspection UnnecessaryContinue
continue;
}
}
}
} catch (IOException e) {
//FIXME the warning message will NPE with what I have :(
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IO Exception attempting to load global transforms:" + e.getMessage(),
null));
}
for (Map.Entry<String, URL> entry : globalTransformNames.entrySet()) {
try {
Class gTransClass = cuLoader.loadClass(entry.getKey());
//noinspection unchecked
GroovyASTTransformation transformAnnotation = (GroovyASTTransformation) gTransClass.getAnnotation(GroovyASTTransformation.class);
if (transformAnnotation == null) {
compilationUnit.getErrorCollector().addWarning(new WarningMessage(
WarningMessage.POSSIBLE_ERRORS,
"Transform Class " + entry.getKey() + " is specified as a global transform in " + entry.getValue().toExternalForm()
+ " but it is not annotated by " + GroovyASTTransformation.class.getName()
+ " the global tranform associated with it may fail and cause the compilation to fail.",
null,
null));
continue;
}
if (ASTTransformation.class.isAssignableFrom(gTransClass)) {
final ASTTransformation instance = (ASTTransformation)gTransClass.newInstance();
compilationUnit.addPhaseOperation(new CompilationUnit.SourceUnitOperation() {
public void call(SourceUnit source) throws CompilationFailedException {
instance.visit(new ASTNode[] {source.getAST()}, source);
}
}, transformAnnotation.phase().getPhaseNumber());
} else {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Transform Class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " is not an ASTTransformation.", null));
}
} catch (Exception e) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Could not instantiate global transform class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " because of exception " + e.toString(), null));
}
}
}
| public static void addGlobalTransforms(CompilationUnit compilationUnit) {
GroovyClassLoader cuLoader = compilationUnit.getClassLoader();
LinkedHashMap<String, URL> globalTransformNames = new LinkedHashMap<String, URL>();
try {
Enumeration<URL> globalServices = cuLoader.getResources("META-INF/services/org.codehaus.groovy.transform.ASTTransformation");
while (globalServices.hasMoreElements()) {
URL service = globalServices.nextElement();
String className;
BufferedReader svcIn = new BufferedReader(new InputStreamReader(service.openStream()));
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
continue;
}
while (className != null) {
if (!className.startsWith("#") && className.length() > 0) {
if (globalTransformNames.containsKey(className)) {
if (!service.equals(globalTransformNames.get(className))) {
compilationUnit.getErrorCollector().addWarning(
WarningMessage.POSSIBLE_ERRORS,
"The global transform for class " + className + " is defined in both "
+ globalTransformNames.get(className).toExternalForm()
+ " and "
+ service.toExternalForm()
+ " - the former definition will be used and the latter ignored.",
null,
null);
}
} else {
globalTransformNames.put(className, service);
}
}
try {
className = svcIn.readLine();
} catch (IOException ioe) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IOException reading the service definition at "
+ service.toExternalForm() + " because of exception " + ioe.toString(), null));
//noinspection UnnecessaryContinue
continue;
}
}
}
} catch (IOException e) {
//FIXME the warning message will NPE with what I have :(
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"IO Exception attempting to load global transforms:" + e.getMessage(),
null));
}
try {
Class.forName("java.lang.annotation.Annotation"); // test for 1.5 JVM
} catch (Exception e) {
// we failed, notify the user
StringBuffer sb = new StringBuffer();
sb.append("Global ASTTransformations are not enabled in retro builds of groovy.\n");
sb.append("The following transformations will be ignored:");
for (Map.Entry<String, URL> entry : globalTransformNames.entrySet()) {
sb.append('\t');
sb.append(entry.getKey());
sb.append('\n');
}
compilationUnit.getErrorCollector().addWarning(new WarningMessage(
WarningMessage.POSSIBLE_ERRORS, sb.toString(), null, null));
return;
}
for (Map.Entry<String, URL> entry : globalTransformNames.entrySet()) {
try {
Class gTransClass = cuLoader.loadClass(entry.getKey());
//noinspection unchecked
GroovyASTTransformation transformAnnotation = (GroovyASTTransformation) gTransClass.getAnnotation(GroovyASTTransformation.class);
if (transformAnnotation == null) {
compilationUnit.getErrorCollector().addWarning(new WarningMessage(
WarningMessage.POSSIBLE_ERRORS,
"Transform Class " + entry.getKey() + " is specified as a global transform in " + entry.getValue().toExternalForm()
+ " but it is not annotated by " + GroovyASTTransformation.class.getName()
+ " the global tranform associated with it may fail and cause the compilation to fail.",
null,
null));
continue;
}
if (ASTTransformation.class.isAssignableFrom(gTransClass)) {
final ASTTransformation instance = (ASTTransformation)gTransClass.newInstance();
compilationUnit.addPhaseOperation(new CompilationUnit.SourceUnitOperation() {
public void call(SourceUnit source) throws CompilationFailedException {
instance.visit(new ASTNode[] {source.getAST()}, source);
}
}, transformAnnotation.phase().getPhaseNumber());
} else {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Transform Class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " is not an ASTTransformation.", null));
}
} catch (Exception e) {
compilationUnit.getErrorCollector().addError(new SimpleMessage(
"Could not instantiate global transform class " + entry.getKey() + " specified at "
+ entry.getValue().toExternalForm() + " because of exception " + e.toString(), null));
}
}
}
|
diff --git a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
index 15e83deb..3fe63399 100644
--- a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
+++ b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
@@ -1,12149 +1,12149 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community 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://www.opensource.org/licenses/ecl1.php
*
* 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.site.tool;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.mailarchive.api.MailArchiveService;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.sitemanage.api.AffiliatedSectionProvider;
import org.sakaiproject.sitemanage.api.SectionField;
import org.sakaiproject.sitemanage.api.SectionFieldProvider;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ArrayUtil;
// import org.sakaiproject.util.CourseIdGenerator;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.SakaiArchive;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.coursemanagement.api.CourseOffering;
import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.coursemanagement.api.Enrollment;
import org.sakaiproject.coursemanagement.api.Membership;
import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException;
import org.sakaiproject.authz.api.GroupProvider;
import org.apache.velocity.tools.generic.SortTool;
/**
* <p>
* SiteAction controls the interface for worksite setup.
* </p>
*/
public class SiteAction extends PagedResourceActionII {
/** Our logger. */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private ImportService importService = org.sakaiproject.importer.cover.ImportService
.getInstance();
/** portlet configuration parameter values* */
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager
.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class);
private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager
.get(org.sakaiproject.authz.api.GroupProvider.class);
private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager
.get(org.sakaiproject.authz.api.AuthzGroupService.class);
private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class);
private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class);
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO = "siteinfo";
private static final String STATE_SITE_MODE = "site_mode";
protected final static String[] TEMPLATE = {
"-list",// 0
"-type",
"-newSiteInformation",
"-newSiteFeatures",
"-addRemoveFeature",
"-addParticipant",
"-removeParticipants",
"-changeRoles",
"-siteDeleteConfirm",
"-publishUnpublish",
"-newSiteConfirm",// 10
"-newSitePublishUnpublish",
"-siteInfo-list",// 12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",// 15
"-publishUnpublish-sendEmail",
"-publishUnpublish-confirm",
"-siteInfo-editAccess",
"-addParticipant-sameRole",
"-addParticipant-differentRole",// 20
"-addParticipant-notification",
"-addParticipant-confirm",
"-siteInfo-editAccess-globalAccess",
"-siteInfo-editAccess-globalAccess-confirm",
"-changeRoles-confirm",// 25
"-modifyENW", "-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",// 30
"",// 31
"",// 32
"",// 33
"",// 34
"",// 35
"-newSiteCourse",// 36
"-newSiteCourseManual",// 37
"",// 38
"",// 39
"",// 40
"",// 41
"-gradtoolsConfirm",// 42
"-siteInfo-editClass",// 43
"-siteInfo-addCourseConfirm",// 44
"-siteInfo-importMtrlMaster", // 45 -- htripath for import
// material from a file
"-siteInfo-importMtrlCopy", // 46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", // 48
"-siteInfo-group", // 49
"-siteInfo-groupedit", // 50
"-siteInfo-groupDeleteConfirm", // 51,
"", // 52 - no template; used by daisyf. for remove course section
"-findCourse" // 53
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
/** Name of state attribute for CHEF site type */
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for poissible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
// Names of state attributes corresponding to properties of a site
private final static String PROP_SITE_CONTACT_EMAIL = "contact-email";
private final static String PROP_SITE_CONTACT_NAME = "contact-name";
private final static String PROP_SITE_TERM = "term";
private final static String PROP_SITE_TERM_EID = "term_eid";
/**
* Name of the state attribute holding the site list column list is sorted
* by
*/
private static final String SORTED_BY = "site.sorted.by";
/** the list of criteria for sorting */
private static final String SORTED_BY_TITLE = "title";
private static final String SORTED_BY_DESCRIPTION = "description";
private static final String SORTED_BY_TYPE = "type";
private static final String SORTED_BY_STATUS = "status";
private static final String SORTED_BY_CREATION_DATE = "creationdate";
private static final String SORTED_BY_JOINABLE = "joinable";
private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name";
private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname";
private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role";
private static final String SORTED_BY_PARTICIPANT_ID = "participant_id";
private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course";
private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits";
private static final String SORTED_BY_MEMBER_NAME = "member_name";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_NEWS_TITLES = "newstitles";
private final static String STATE_NEWS_URLS = "newsurls";
private final static String NEWS_DEFAULT_TITLE = ServerConfigurationService
.getString("news.title");
private final static String NEWS_DEFAULT_URL = ServerConfigurationService
.getString("news.feedURL");
private final static String STATE_WEB_CONTENT_TITLES = "webcontenttitles";
private final static String STATE_WEB_CONTENT_URLS = "wcUrls";
private final static String WEB_CONTENT_DEFAULT_TITLE = "Web Content";
private final static String WEB_CONTENT_DEFAULT_URL = "http://";
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or
// ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the
// list
// of
// site
// pages
// consistent
// with
// Worksite
// Setup
// page
// patterns
/**
* The name of the state form field containing additional information for a
* course request
*/
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state */
private final static String FORM_TITLE = "form_title";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
/** site info edit form variables */
private final static String FORM_SITEINFO_TITLE = "siteinfo_title";
private final static String FORM_SITEINFO_TERM = "siteinfo_term";
private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description";
private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description";
private final static String FORM_SITEINFO_SKIN = "siteinfo_skin";
private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include";
private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url";
private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name";
private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles */
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
// site template used to create a UM Grad Tools student site
public static final String SITE_GTS_TEMPLATE = "!gtstudent";
// the type used to identify a UM Grad Tools student site
public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent";
// list of UM Grad Tools site types for editing
public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// used for site creation wizard title
public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps";
public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step";
// types of site whose title can be editable
public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
// htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES = "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName";
private static final String SESSION_CONTEXT_ID = "sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
// group info
private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id";
private static final String STATE_GROUP_TITLE = "state_group_title";
private static final String STATE_GROUP_DESCRIPTION = "state_group_description";
private static final String STATE_GROUP_MEMBERS = "state_group_members";
private static final String STATE_GROUP_REMOVE = "state_group_remove";
private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
private static final String EMAIL_CHAR = "@";
// Special tool id for Home page
private static final String HOME_TOOL_ID = "home";
private static final String STATE_CM_LEVELS = "site.cm.levels";
private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections";
private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection";
private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested";
private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list";
private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId";
private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list";
private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections";
private String cmSubjectCategory;
private boolean warnedNoSubjectCategory = false;
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar";
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet,
JetspeedRunData rundata) {
super.initState(state, portlet, rundata);
// store current userId in state
User user = UserDirectoryService.getCurrentUser();
String userId = user.getEid();
state.setAttribute(STATE_CM_CURRENT_USERID, userId);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtil.trimToNull(config
.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) {
if (changeableTypes != null) {
state
.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new ArrayList(Arrays.asList(changeableTypes
.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtil.trimToNull(config
.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) {
if (publicTypes != null) {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(
Arrays.asList(publicTypes.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtil.trimToNull(config
.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) {
if (privateTypes != null) {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(
Arrays.asList(privateTypes.split(","))));
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtil.trimToNull(config
.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) {
if (defaultType != null) {
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) {
if (ServerConfigurationService
.getStrings("wsetup.disable.joinable") != null) {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new ArrayList(Arrays.asList(ServerConfigurationService
.getStrings("wsetup.disable.joinable"))));
} else {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new Vector());
}
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) {
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
// skins if any
if (state.getAttribute(STATE_ICONS) == null) {
setupIcons(state);
}
if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) {
List gradToolsSiteTypes = new Vector();
if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) {
gradToolsSiteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("gradToolsSiteType")));
}
state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes);
}
if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("titleEditableSiteType"))));
} else {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector());
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) {
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) {
siteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
// get site tool mode from tool registry
String site_mode = portlet.getPortletConfig().getInitParameter(
STATE_SITE_MODE);
state.setAttribute(STATE_SITE_MODE, site_mode);
} // initState
/**
* cleanState removes the current site instance and it's properties from
* state
*/
private void cleanState(SessionState state) {
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_COURSE_HASH);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_INSTRUCTOR_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_PROVIDER_SECTION_LIST);
state.removeAttribute(STATE_CM_LEVELS);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_CURRENT_USERID);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL); // don't we need to clena this
// too? -daisyf
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context) {
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null
&& ((String) state.getAttribute(STATE_SITE_MODE))
.equals(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
Site s = getStateSite(state);
if (s != null) {
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using
// the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb
.getString("setperfor")
+ " " + SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for normal display
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
context.put("tlang", rb);
// TODO: what is all this doing? if we are in helper mode, we are
// already setup and don't get called here now -ggolden
/*
* String helperMode = (String)
* state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode !=
* null) { Site site = getStateSite(state); if (site != null) { if
* (site.getType() != null && ((List)
* state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) {
* context.put("editViewRoster", Boolean.TRUE); } else {
* context.put("editViewRoster", Boolean.FALSE); } } else {
* context.put("editViewRoster", Boolean.FALSE); } // for new, don't
* show site.del in Permission page context.put("hiddenLock",
* "site.del");
*
* String template = PermissionsAction.buildHelperContext(portlet,
* context, data, state); if (template == null) { addAlert(state,
* rb.getString("theisa")); } else { return template; } }
*/
String template = null;
context.put("action", CONTEXT_ACTION);
// updatePortlet(state, portlet, data);
if (state.getAttribute(STATE_INITIALIZED) == null) {
init(portlet, data, state);
}
int index = Integer.valueOf(
(String) state.getAttribute(STATE_TEMPLATE_INDEX)).intValue();
template = buildContextForTemplate(index, portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* Build the context for each template using template_index parameter passed
* in a form hidden field. Each case is associated with a template. (Not all
* templates implemented). See String[] TEMPLATES.
*
* @param index
* is the number contained in the template's template_index
*/
private String buildContextForTemplate(int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
// the Grad Tools site option is only presented to
// GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a grad student?
if (!isGradToolsCandidate(userId)) {
// not a gradstudent
remove = true;
}
} catch (Exception e) {
remove = true;
}
} else {
// not support for dissertation sites
remove = true;
}
// do not show this site type in views
// sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
// the Grad Tools site option is only presented to UM grad
// students
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a UM grad student?
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
// if I am a UM grad student, do I already have a Grad Tools
// site?
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
if (Log.isWarnEnabled()) {
M_log.warn("buildContextForTemplate chef_site-type.vm "
+ e);
}
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) {
context.put("typeSelected", siteInfo.site_type);
} else if (types.size() > 0) {
context.put("typeSelected", types.get(0));
}
setTermListForContext(context, state, true); // true => only
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
/*
* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
context.put("back", "53");
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
context.put("back", "36");
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
} else {
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "0");
context.put("template-index", "37");
}
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put("back", "1");
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
/*
* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// ToolRegistrations
// for
// template
// list
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
// The "Home" tool checkbox needs special treatment to be selected
// by
// default.
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
/*
* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
// Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
// get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
/*
* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties
// and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService
.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService
.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService
.getString("emailInIdAccountLabel"));
if (state.getAttribute("noEmailInIdAccountValue") != null) {
context.put("noEmailInIdAccountValue", (String) state
.getAttribute("noEmailInIdAccountValue"));
}
if (state.getAttribute("emailInIdAccountValue") != null) {
context.put("emailInIdAccountValue", (String) state
.getAttribute("emailInIdAccountValue"));
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 6:
/*
* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try {
List removeableList = (List) state
.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++) {
User user = UserDirectoryService
.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null) {
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
} catch (UserNotDefinedException ee) {
}
} catch (GroupNotDefinedException e) {
}
context.put("backIndex", "18");
return (String) getContext(data).get("template") + TEMPLATE[6];
case 7:
/*
* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[7];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 9:
/*
* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo) state
.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[9];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 11:
/*
* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[11];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite) {
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site access for GRADTOOLS
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course")) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site duplicate and import
// for GRADTOOLS type of sites
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership) {
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
// show the Add Participant menu
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,
sortedAsc));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants
.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties()
.getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null) {
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1) {
manualCourseList = new ArrayList(
Arrays.asList(manualCourseListString
.split("\\+")));
} else {
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try {
context.put("realm", AuthzGroupService
.getAuthzGroup(realmId));
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + realmId);
}
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null) {
context.put("selectedIcon", state
.getAttribute(FORM_SITEINFO_SKIN));
} else if (site.getIconUrl() != null) {
context.put("selectedIcon", site.getIconUrl());
}
setTermListForContext(context, state, true); // true->only future terms
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
// Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with
// sakai.properties file.
if ((ServerConfigurationService
.getString("disable.course.site.skin.selection"))
.equals("true")) {
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state)) {
context.put("back", "26");
} else {
context.put("back", "4");
}
return (String) getContext(data).get("template") + TEMPLATE[15];
case 16:
/*
* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[16];
case 17:
/*
* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished()) {
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
} else {
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[17];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state)) {
context.put("back", "26");
} else if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
/*
* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
/*
* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
/*
* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
/*
* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 23:
/*
* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null) {
state.setAttribute("form_joinable", new Boolean(site
.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null) {
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[23];
case 24:
/*
* buildContextForTemplate
* chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[24];
case 25:
/*
* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state
.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue()) {
// same role
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
} else {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[25];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
// titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null) {
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
// urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null) {
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null) {
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
// URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null) {
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
- getToolsAvailableForImport(state))); // String toolId's
+ (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
setTermListForContext(context, state, true); // true-> upcoming only
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true); // true -> upcoming only
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state
.getAttribute(SITE_MANUAL_COURSE_LIST));
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (!providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
/*
List list1 = prepareSectionObject(providerSectionList,
(String) state
.getAttribute(STATE_CM_CURRENT_USERID));
*/
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number - 1));
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("requestedSections", l);
}
// v2.4 - added & modified by daisyf
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "1");
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
// context.put("back", "36");
} else {
context.put("back", "1");
}
}
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
/*
* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
/*
* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
/*
* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
final List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
Object levelOpts[] = new Object[cmLevels.size()];
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
// populate options for dropdown lists
switch (numSelections) {
/*
* execution will fall through these statements based on number
* of selections already made
*/
case 3:
// intentionally blank
case 2:
levelOpts[2] = getCMSections((String) selections.get(1));
case 1:
levelOpts[1] = getCMCourseOfferings((String) selections
.get(0), t.getEid());
default:
levelOpts[0] = getCMSubjects();
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("requestedSections", requestedSections);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "36");
}
// else if (((String) state.getAttribute(STATE_SITE_MODE))
// .equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// context.put("backIndex", "");
// }
return (String) getContext(data).get("template") + TEMPLATE[53];
}
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
/**
* Launch the Page Order Helper Tool -- for ordering, adding and customizing
* pages
*
* @see case 12
*
*/
public void doPageOrderHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
// htripath: import materials from classic
/**
* Master import -- for import materials from a file
*
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// state.setAttribute(FILE_UPLOAD_MAX_SIZE,
// ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
*
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString(
"content.upload.max", "1");
int max_bytes = 1024 * 1024;
try {
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
} catch (Exception e) {
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if (fileFromUpload == null) {
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("importFile.size") + " "
+ max_file_size_mb + "MB "
+ rb.getString("importFile.exceeded"));
} else if (fileFromUpload.getFileName() == null
|| fileFromUpload.getFileName().length() == 0) {
addAlert(state, rb.getString("importFile.choosefile"));
} else {
byte[] fileData = fileFromUpload.get();
if (fileData.length >= max_bytes) {
addAlert(state, rb.getString("size") + " " + max_file_size_mb
+ "MB " + rb.getString("importFile.exceeded"));
} else if (fileData.length > 0) {
if (importService.isValidArchive(fileData)) {
ImportDataSource importDataSource = importService
.parseFromFile(fileData);
Log.info("chef", "Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0) {
Iterator iter = lst.iterator();
while (iter.hasNext()) {
ImportMetadata importdata = (ImportMetadata) iter
.next();
// Log.info("chef","Preparing import
// item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName()
.endsWith(".xml"))) {
allzipList.add(importdata);
} else {
directcopyList.add(importdata);
}
}
}
// set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
*
* @param data
*/
public void doAdd_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
*
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items) {
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++) {
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId())) {
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
*
* @param data
*/
public void doRemove_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
*
* @param data
*/
public void doCopyMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
*
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state
.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size()
+ " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is "
+ importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef",
"doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive) importDataSource).buildSourceFolder(fnlList);
Log.info("chef", "doSaveMtrlSite() source folder is "
+ ((SakaiArchive) importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive) importDataSource)
.getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource
.getItemsForCategories(fnlList), siteId);
}
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
// state.setAttribute(STATE_TEMPLATE_INDEX, "28");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
// htripath-end
/**
* Handle the site search request.
*/
public void doSite_search(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the search form field into the state object
String search = StringUtil.trimToNull(data.getParameters().getString(
FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null) {
state.removeAttribute(STATE_SEARCH);
} else {
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
*/
public void doSite_search_clear(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
private void coursesIntoContext(SessionState state, Context context,
Site site) {
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = StringUtil.trimToNull(site
.getProperties().getProperty(PROP_SITE_REQUEST_COURSE));
if (manualCourseListString != null) {
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1) {
manualCourseList = new ArrayList(Arrays
.asList(manualCourseListString.split("\\+")));
} else {
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
context.put("manualCourseList", manualCourseList);
}
}
/**
* buildInstructorSectionsList Build the CourseListItem list for this
* Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state,
ParameterParser params, Context context) {
// Site information
// The sections of the specified term having this person as Instructor
context.put("providerCourseSectionList", state
.getAttribute("providerCourseSectionList"));
context.put("manualCourseSectionList", state
.getAttribute("manualCourseSectionList"));
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
setTermListForContext(context, state, true); //-> future terms only
context.put(STATE_TERM_COURSE_LIST, state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang", rb);
} // buildInstructorSectionsList
/**
* getProviderCourseList a course site/realm id in one of three formats, for
* a single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses. getProviderCourseList parses a
* realm id into year, term, campus_code, catalog_nbr, section components.
*
* @param id
* is a String representation of the course realm id (external
* id).
*/
private List getProviderCourseList(String id) {
Vector rv = new Vector();
if (id == null || id == NULL_STRING) {
return rv;
}
// Break Provider Id into course id parts
String[] courseIds = groupProvider.unpackId(id);
// Iterate through course ids
for (int i=0; i<courseIds.length; i++) {
String courseId = (String) courseIds[i];
rv.add(courseId);
}
return rv;
} // getProviderCourseList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state) {
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using
// the criteria
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null);
} else if (view.equals(rb.getString("java.my"))) {
// search for a specific user site
// for the particular user id in the
// criteria - exact match only
try {
SiteService.getSite(SiteService
.getUserSiteId(search));
size++;
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
view, search, null);
}
}
} else {
Site userWorkspaceSite = null;
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
size++;
}
} else {
size++;
}
}
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null);
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null);
}
}
}
}
// for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List l = (List) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l != null) ? l.size() : 0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last) {
String search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (new Boolean((String) state
.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString())) {
sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC;
} else if (sortBy.equals(SortType.TYPE_ASC.toString())) {
sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC;
} else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_BY_ASC
: SortType.CREATED_BY_DESC;
} else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_ON_ASC
: SortType.CREATED_ON_DESC;
} else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) {
sortType = sortAsc ? SortType.PUBLISHED_ASC
: SortType.PUBLISHED_DESC;
}
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using the
// criteria
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null, sortType,
new PagingPosition(first, last));
} else if (view.equalsIgnoreCase(rb.getString("java.my"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
List rv = new Vector();
try {
Site userSite = SiteService.getSite(SiteService
.getUserSiteId(search));
rv.add(userSite);
} catch (IdUnusedException e) {
}
return rv;
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last));
} else {
// search for a specific site
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, null, sortType,
new PagingPosition(first, last));
}
}
} else {
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
rv.add(userWorkspaceSite);
}
} else {
rv.add(userWorkspaceSite);
}
}
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null, sortType,
new PagingPosition(first, last)));
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last)));
} else {
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null, sortType,
new PagingPosition(first, last)));
}
}
return rv;
}
}
// if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? (List) state
.getAttribute(STATE_PARTICIPANT_LIST)
: new Vector();
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst() - 1, page
.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params,
SessionState state) {
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String
// toolId's
for (int i = 0; i < selectedTools.size(); i++) {
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null) {
importTools.put(toolId, new ArrayList(Arrays.asList(params
.getStrings(toolId))));
if (!anyToolSelected) {
anyToolSelected = true;
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
*
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state) {
boolean fromENW = false;
List oTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
for (int i = 0; i < toolList.size() && !fromENW; i++) {
String toolId = (String) toolList.get(i);
if (toolId.equals("sakai.mailbox")
|| toolId.indexOf("sakai.news") != -1
|| toolId.indexOf("sakai.iframe") != -1) {
if (oTools == null) {
// if during site creation proces
fromENW = true;
} else if (!oTools.contains(toolId)) {
// if user is adding either EmailArchive tool, News tool or
// Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// start clean
cleanState(state);
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null) {
if (siteTypes.size() == 1) {
String siteType = (String) siteTypes.get(0);
if (!siteType.equals(ServerConfigurationService.getString(
"courseSiteType", ""))) {
// if only one site type is allowed and the type isn't
// course type
// skip the select site type step
setNewSiteType(state, siteType);
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is
* clicked
*
*/
public void doMenu_site_delete(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals);
// present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
public void doSite_delete_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
M_log
.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the
// site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
if (!chosenList.isEmpty()) {
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String id = (String) i.next();
String site_title = NULL_STRING;
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " " + id
+ " " + rb.getString("java.couldnt") + " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site site = SiteService.getSite(id);
site_title = site.getTitle();
SiteService.removeSite(site);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ site_title + "(" + id + ") "
+ rb.getString("java.couldnt") + " ");
} catch (PermissionException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - PermissionException, site "
+ site_title + "(" + id + ").");
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
} else {
M_log
.warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site "
+ id);
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site
// list
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
*
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state) {
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
try {
site = SiteService.getSite((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return site;
} // getStateSite
/**
* get the Group object based on SessionState attribute values
*
* @return Group object related to current state; null if no such Group
* object could be found
*/
protected Group getStateGroup(SessionState state) {
Group group = null;
Site site = getStateSite(state);
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return group;
} // getStateGroup
/**
* do called when "eventSubmit_do" is in the request parameters to c is
* called from site list menu entry Revise... to get a locked site as
* editable and to go to the correct template to begin DB version of writes
* changes to disk at site commit whereas XML version writes at server
* shutdown
*/
public void doGet_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// check form filled out correctly
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
String siteId = "";
if (!chosenList.isEmpty()) {
if (chosenList.size() != 1) {
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
// reset the paging info
resetPaging(state);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_PAGESIZE_SITESETUP, state
.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// when first entered Site Info, set the participant list size to
// 200 as default
state.setAttribute(STATE_PAGESIZE, new Integer(200));
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
} else {
// restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// create a new Site object based on selected Site object and put in
// state
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// get site as Site object, check SiteCreationStatus and SiteType of
// site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request
* parameters
*/
public void doView_sites(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView(RunData data) throws Exception {
// called from chef_site-list.vm with a select option to build query of
// sites
//
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type(RunData data) {
/*
* for measuring how long it takes to load sections java.util.Date date =
* new java.util.Date(); M_log.debug("***1. start preparing
* section:"+date);
*/
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
String type = StringUtil.trimToNull(params.getString("itemType"));
int totalSteps = 0;
if (type == null) {
addAlert(state, rb.getString("java.select") + " ");
} else {
setNewSiteType(state, type);
if (type.equalsIgnoreCase("course")) {
User user = UserDirectoryService.getCurrentUser();
String currentUserId = user.getEid();
String userId = params.getString("userId");
if (userId == null || "".equals(userId)) {
userId = currentUserId;
} else {
// implies we are trying to pick sections owned by other
// users. Currently "select section by user" page only
// take one user per sitte request - daisy's note 1
ArrayList<String> list = new ArrayList();
list.add(userId);
state.setAttribute(STATE_CM_AUTHORIZER_LIST, list);
}
state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId);
String academicSessionEid = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(academicSessionEid);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null) {
List sections = prepareCourseAndSectionListing(userId, t
.getEid(), state);
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try {
weeks = Integer
.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
c.add(Calendar.DATE, weeks * 7);
} catch (Exception ignore) {
}
if (c.getTimeInMillis() < t.getStartDate().getTime()) {
// if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
if (sections != null && sections.size() > 0) {
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
// v2.4 added by daisyf
if (courseManagementIsImplemented()) {
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
totalSteps = 5;
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
totalSteps = 6;
}
} else { // type!="course"
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
} else if (type.equals("project")) {
totalSteps = 4;
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
// if a GradTools site use pre-defined site info and exclude
// from public listing
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
siteInfo.title = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.description = rb.getString("java.gradsite") + " "
+ currentUser.getDisplayName();
siteInfo.short_description = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// skip directly to confirm creation of site
state.setAttribute(STATE_TEMPLATE_INDEX, "42");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) {
state
.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(
totalSteps));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1));
}
} // doSite_type
public void doChange_user(RunData data) {
doSite_type(data);
} // doChange_user
/**
* cleanEditGroupParams clean the state parameters used by editing group
* process
*
*/
public void cleanEditGroupParams(SessionState state) {
state.removeAttribute(STATE_GROUP_INSTANCE_ID);
state.removeAttribute(STATE_GROUP_TITLE);
state.removeAttribute(STATE_GROUP_DESCRIPTION);
state.removeAttribute(STATE_GROUP_MEMBERS);
state.removeAttribute(STATE_GROUP_REMOVE);
} // cleanEditGroupParams
/**
* doGroup_edit
*
*/
public void doGroup_update(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
Site site = getStateSite(state);
String title = StringUtil.trimToNull(params.getString(rb
.getString("group.title")));
state.setAttribute(STATE_GROUP_TITLE, title);
String description = StringUtil.trimToZero(params.getString(rb
.getString("group.description")));
state.setAttribute(STATE_GROUP_DESCRIPTION, description);
boolean found = false;
String option = params.getString("option");
if (option.equals("add")) {
// add selected members into it
if (params.getStrings("generallist") != null) {
List addMemberIds = new ArrayList(Arrays.asList(params
.getStrings("generallist")));
for (int i = 0; i < addMemberIds.size(); i++) {
String aId = (String) addMemberIds.get(i);
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
if (((Member) iSet.next()).getUserEid().equals(aId)) {
found = true;
}
}
if (!found) {
try {
User u = UserDirectoryService.getUser(aId);
gMemberSet.add(site.getMember(u.getId()));
} catch (UserNotDefinedException e) {
try {
User u2 = UserDirectoryService
.getUserByEid(aId);
gMemberSet.add(site.getMember(u2.getId()));
} catch (UserNotDefinedException ee) {
M_log.warn(this + ee.getMessage() + aId);
}
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("remove")) {
// update the group member list by remove selected members from it
if (params.getStrings("grouplist") != null) {
List removeMemberIds = new ArrayList(Arrays.asList(params
.getStrings("grouplist")));
for (int i = 0; i < removeMemberIds.size(); i++) {
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
Member mSet = (Member) iSet.next();
if (mSet.getUserId().equals(
(String) removeMemberIds.get(i))) {
found = true;
gMemberSet.remove(mSet);
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("cancel")) {
// cancel from the update the group member process
doCancel(data);
cleanEditGroupParams(state);
} else if (option.equals("save")) {
Group group = null;
if (site != null
&& state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
if (title == null) {
addAlert(state, rb.getString("editgroup.titlemissing"));
} else {
if (group == null) {
// when adding a group, check whether the group title has
// been used already
boolean titleExist = false;
for (Iterator iGroups = site.getGroups().iterator(); !titleExist
&& iGroups.hasNext();) {
Group iGroup = (Group) iGroups.next();
if (iGroup.getTitle().equals(title)) {
// found same title
titleExist = true;
}
}
if (titleExist) {
addAlert(state, rb.getString("group.title.same"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (group == null) {
// adding new group
group = site.addGroup();
group.getProperties().addProperty(
GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null) {
group.setTitle(title);
group.setDescription(description);
// save the modification to group members
// remove those no longer included in the group
Set members = group.getMembers();
for (Iterator iMembers = members.iterator(); iMembers
.hasNext();) {
found = false;
String mId = ((Member) iMembers.next()).getUserId();
for (Iterator iMemberSet = gMemberSet.iterator(); !found
&& iMemberSet.hasNext();) {
if (mId.equals(((Member) iMemberSet.next())
.getUserId())) {
found = true;
}
}
if (!found) {
group.removeMember(mId);
}
}
// add those seleted members
for (Iterator iMemberSet = gMemberSet.iterator(); iMemberSet
.hasNext();) {
String memberId = ((Member) iMemberSet.next())
.getUserId();
if (group.getUserRole(memberId) == null) {
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
// for every member added through the "Manage
// Groups" interface, he should be defined as
// non-provided
group.addMember(memberId, r != null ? r.getId()
: "", m != null ? m.isActive() : true,
false);
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
} catch (PermissionException e) {
}
// return to group list view
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
cleanEditGroupParams(state);
}
}
}
}
} // doGroup_updatemembers
/**
* doGroup_new
*
*/
public void doGroup_new(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, "");
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, "");
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
state.setAttribute(STATE_GROUP_MEMBERS, new HashSet());
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_new
/**
* doGroup_edit
*
*/
public void doGroup_edit(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String groupId = data.getParameters().getString("groupId");
state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId);
Site site = getStateSite(state);
if (site != null) {
Group g = site.getGroup(groupId);
if (g != null) {
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, g.getTitle());
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, g
.getDescription());
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
// double check the member existance
Set gMemberSet = g.getMembers();
Set rvGMemberSet = new HashSet();
for (Iterator iSet = gMemberSet.iterator(); iSet.hasNext();) {
Member member = (Member) iSet.next();
try {
UserDirectoryService.getUser(member.getUserId());
((Set) rvGMemberSet).add(member);
} catch (UserNotDefinedException e) {
// cannot find user
M_log.warn(this + rb.getString("user.notdefined")
+ member.getUserId());
}
}
state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet);
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_edit
/**
* doGroup_remove_prep Go to confirmation page before deleting group(s)
*
*/
public void doGroup_remove_prep(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = data.getParameters().getStrings(
"removeGroups");
if (removeGroupIds.length > 0) {
state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds);
state.setAttribute(STATE_TEMPLATE_INDEX, "51");
}
} // doGroup_remove_prep
/**
* doGroup_remove_confirmed Delete selected groups after confirmation
*
*/
public void doGroup_remove_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = (String[]) state
.getAttribute(STATE_GROUP_REMOVE);
Site site = getStateSite(state);
for (int i = 0; i < removeGroupIds.length; i++) {
if (site != null) {
Group g = site.getGroup(removeGroupIds[i]);
if (g != null) {
site.removeGroup(g);
}
}
}
try {
SiteService.save(site);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("editgroup.site.notfound.alert"));
} catch (PermissionException e) {
addAlert(state, rb.getString("editgroup.site.permission.alert"));
}
if (state.getAttribute(STATE_MESSAGE) == null) {
cleanEditGroupParams(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
}
} // doGroup_remove_confirmed
/**
* doMenu_edit_site_info The menu choice to enter group view
*
*/
public void doMenu_group(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset sort criteria
state.setAttribute(SORTED_BY, rb.getString("group.title"));
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
} // doMenu_group
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doManual_add_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) {
readCourseSectionInfo(state, params);
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (getStateSite(state) == null) {
// creating new site
updateSiteInfo(params, state);
}
if (option.equalsIgnoreCase("add")) {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null) {
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("noEmailInIdAccountName")
+ ". ");
} else {
try {
UserDirectoryService.getUserByEid(uniqname);
} catch (UserNotDefinedException e) {
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("noEmailInIdAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
updateCurrentStep(state, true);
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
}
} // doManual_add_course
/**
* read the input information of subject, course and section in the manual
* site creation page
*/
private void readCourseSectionInfo(SessionState state,
ParameterParser params) {
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
oldNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++) {
List requiredFields = sectionFieldProvider.getRequiredFields();
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k < requiredFields.size(); k++) {
SectionField sectionField = (SectionField) requiredFields
.get(k);
String fieldLabel = sectionField.getLabelKey();
String fieldInput = StringUtil.trimToZero(params
.getString(fieldLabel + i));
sectionField.setValue(fieldInput);
aCourseInputs.add(sectionField);
if (fieldInput.length() == 0) {
// is this an empty String input?
emptyInputNum++;
}
// add to the multiCourseInput vector
}
multiCourseInputs.add(i, aCourseInputs);
// is any input invalid?
if (emptyInputNum == 0) {
// valid if all the inputs are not empty
validInputSites++;
} else if (emptyInputNum == requiredFields.size()) {
// ignore if all inputs are empty
} else {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if future term selected, then not all fields are required
// %%%
validInputSites++;
} else {
validInput = false;
}
}
}
// how many more course/section to include in the site?
String option = params.getString("option");
if (option.equalsIgnoreCase("change")) {
if (params.getString("number") != null) {
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
oldNumber + newNumber));
List requiredFields = sectionFieldProvider.getRequiredFields();
for (int j = 0; j < newNumber; j++) {
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m < requiredFields.size(); m++) {
aCourseInputs = sectionFieldProvider.getRequiredFields();
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change")) {
if (!validInput || validInputSites == 0) {
// not valid input
addAlert(state, rb.getString("java.miss"));
} else {
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
validInputSites));
}
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params
.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// store the manually requested sections in one site property
if ((providerCourseList == null || providerCourseList.size() == 0)
&& multiCourseInputs.size() > 0) {
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(),
(List) multiCourseInputs.get(0));
// default title
String title = sectionEid;
try {
title = cms.getSection(sectionEid).getTitle();
} catch (Exception e) {
// ignore
}
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // readCourseSectionInfo
/**
* set the site type for new site
*
* @param type
* The type String
*/
private void setNewSiteType(SessionState state, String type) {
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
// start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// get registered tools list
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
tools.add(newTool);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute(STATE_SITE_TYPE, type);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the field on which to sort the student list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// call this method at the start of a sort for proper paging
resetPaging(state);
// get the field on which to sort the site list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} // doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request
* parameters
*/
public void doContinue(RunData data) {
// Put current form data in state and continue to the next template,
// make any permanent changes
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
// Let actionForTemplate know to make any permanent changes before
// continuing to the next template
String direction = "continue";
String option = params.getString("option");
actionForTemplate(direction, index, params, state);
if (state.getAttribute(STATE_MESSAGE) == null) {
if (index == 9) {
// go to the send site publish email page if "publish" option is
// chosen
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished()) {
state.setAttribute(STATE_TEMPLATE_INDEX, "16");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "17");
}
} else if (index == 36 && ("add").equals(option)) {
// this is the Add extra Roster(s) case after a site is created
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else if (params.getString("continue") != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
}
}// doContinue
/**
* handle with continue add new course site options
*
*/
public void doContinue_new_course(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("continue")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
}
} // doContinue_new_course
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward
* direction
*/
public void doBack(RunData data) {
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int currentIndex = Integer.parseInt((String) state
.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
// Let actionForTemplate know not to make any permanent changes before
// continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an
* unpublished site
*/
public void doFinish(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
addNewSite(params, state);
addFeatures(state);
Site site = getStateSite(state);
// for course sites
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
String siteId = site.getId();
ResourcePropertiesEdit rp = site.getPropertiesEdit();
AcademicSession term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(PROP_SITE_TERM, term.getTitle());
rp.addProperty(PROP_SITE_TERM_EID, term.getEid());
}
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
}
List<SectionObject> cmRequestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null)
&& (providerCourseList.size() != 0)) {
String providerRealm = buildExternalRealm(siteId, state,
providerCourseList);
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realm);
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log
.warn(this
+ " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
return;
}
// catch (AuthzPermissionException e)
// {
// M_log.warn(this + " PermissionException, user does not
// have permission to edit AuthzGroup object.");
// addAlert(state, rb.getString("java.notaccess"));
// return;
// }
catch (Exception e) {
addAlert(state, this + rb.getString("java.problem"));
return;
}
sendSiteNotification(state, providerCourseList);
}
if (manualAddNumber != 0) {
// set the manual sections to the site property
String manualSections = "";
// manualCourseInputs is a list of a list of SectionField
List manualCourseInputs = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < manualAddNumber; j++) {
manualSections = manualSections.concat(
sectionFieldProvider.getSectionEid(
term.getEid(),
(List) manualCourseInputs.get(j)))
.concat("+");
}
// trim the trailing plus sign
if (manualSections.endsWith("+")) {
manualSections = manualSections.substring(0,
manualSections.lastIndexOf("+"));
}
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber,
manualCourseInputs);
}
if (cmRequestedSections != null
&& cmRequestedSections.size() > 0) {
sendSiteRequest(state, "new", cmRequestedSections);
}
if (cmAuthorizerSections != null
&& cmAuthorizerSections.size() > 0) {
sendSiteRequest(state, "new", cmAuthorizerSections);
}
}
// commit site
commitSite(site);
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
// now that the site exists, we can set the email alias when an
// Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(siteId);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
/**
* buildExternalRealm creates a site/realm id in one of three formats, for a
* single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses
*
* @param sectionList
* is a Vector of CourseListItem
* @param id
* The site id
*/
private String buildExternalRealm(String id, SessionState state,
List<String> providerIdList) {
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm)) {
addAlert(state, rb.getString("java.rosters"));
return null;
}
String[] providers = new String[providerIdList.size()];
providers = (String[]) providerIdList.toArray(providers);
String providerId = groupProvider.packId(providers);
return providerId;
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request,
int requestListSize, List requestFields) {
User cUser = UserDirectoryService.getCurrentUser();
boolean sendEmailToRequestee = false;
StringBuffer buf = new StringBuffer();
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
String noEmailInIdAccountName = ServerConfigurationService
.getString("noEmailInIdAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if (request.equals("new")) {
additional = siteInfo.getAdditional();
} else {
additional = (String) state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// message subject
if (termExist) {
message_subject = rb.getString("java.sitereqfrom") + " "
+ sessionUserName + " " + rb.getString("java.for")
+ " " + term.getEid();
} else {
message_subject = rb.getString("java.official") + " "
+ sessionUserName;
}
// there is no offical instructor for future term sites
String requestId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (!isFutureTerm) {
// To site quest account - the instructor of record's
if (requestId != null) {
try {
User instructor = UserDirectoryService
.getUser(requestId);
from = requestEmail;
to = instructor.getEmail();
headerTo = instructor.getEmail();
replyTo = requestEmail;
buf.append(rb.getString("java.hello") + " \n\n");
buf.append(rb.getString("java.receiv") + " "
+ sessionUserName + ", ");
buf.append(rb.getString("java.who") + "\n");
if (termExist) {
buf.append(term.getTitle());
}
// requsted sections
addRequestedSectionIntoNotification(state, requestFields, buf);
buf.append("\n" + rb.getString("java.sitetitle") + "\t"
+ title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id);
buf.append("\n\n" + rb.getString("java.according")
+ " " + sessionUserName + " "
+ rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou") + " "
+ sessionUserName + " "
+ rb.getString("java.assoc") + "\n\n");
buf.append(rb.getString("java.respond") + " "
+ sessionUserName
+ rb.getString("java.appoint") + "\n\n");
buf.append(rb.getString("java.thanks") + "\n");
buf.append(productionSiteName + " "
+ rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject, content,
headerTo, replyTo, null);
// email has been sent successfully
sendEmailToRequestee = true;
} catch (UserNotDefinedException ee) {
} // try
}
}
// To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to") + "\t\t" + productionSiteName
+ " " + rb.getString("java.supp") + "\n");
buf.append("\n" + rb.getString("java.from") + "\t"
+ sessionUserName + "\n");
if (request.equals("new")) {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitereq") + "\n");
} else {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitechreq") + "\n");
}
buf.append(rb.getString("java.date") + "\t" + local_date + " "
+ local_time + "\n\n");
if (request.equals("new")) {
buf.append(rb.getString("java.approval") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
} else {
buf.append(rb.getString("java.approval2") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
}
if (termExist) {
buf.append(term.getTitle());
}
if (requestListSize > 1) {
buf.append(" " + rb.getString("java.forthese") + " "
+ requestListSize + " " + rb.getString("java.sections")
+ "\n\n");
} else {
buf.append(" " + rb.getString("java.forthis") + "\n\n");
}
// what are the required fields shown in the UI
addRequestedSectionIntoNotification(state, requestFields, buf);
buf.append(rb.getString("java.name") + "\t" + sessionUserName
+ " (" + noEmailInIdAccountName + " " + cUser.getEid()
+ ")\n");
buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id + "\n");
buf.append(rb.getString("java.siteinstr") + "\n" + additional
+ "\n\n");
if (!isFutureTerm) {
if (sendEmailToRequestee) {
buf.append(rb.getString("java.authoriz") + " " + requestId
+ " " + rb.getString("java.asreq"));
} else {
buf.append(rb.getString("java.thesiteemail") + " "
+ requestId + " " + rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
// To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing") + " ");
buf.append(rb.getString("java.meantime") + "\n\n");
buf.append(rb.getString("java.copy") + "\n\n");
buf.append(content);
buf.append("\n" + rb.getString("java.wish") + " " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuffer buf) {
// what are the required fields shown in the UI
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
for (int i = 0; i < requiredFields.size(); i++) {
List requiredFieldList = (List) requestFields
.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList
.get(j);
buf.append(requiredField.getLabelKey() + "\t"
+ requiredField.getValue() + "\n");
}
}
}
private void sendSiteRequest(SessionState state, String request,
List<SectionObject> cmRequestedSections) {
User cUser = UserDirectoryService.getCurrentUser();
boolean sendEmailToRequestee = false;
StringBuffer buf = new StringBuffer();
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
String noEmailInIdAccountName = ServerConfigurationService
.getString("noEmailInIdAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
/*
* I don't understand the following logic, why isn't aditional info
* be included when it is a new request? -daisyf
*/
/*
* So I am commented this out if (request.equals("new")) {
* additional = siteInfo.getAdditional(); } else { additional =
* (String) state.getAttribute(FORM_ADDITIONAL); }
*/
additional = (String) state.getAttribute(FORM_ADDITIONAL);
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// message subject
if (termExist) {
message_subject = rb.getString("java.sitereqfrom") + " "
+ sessionUserName + " " + rb.getString("java.for")
+ " " + term.getEid();
} else {
message_subject = rb.getString("java.official") + " "
+ sessionUserName;
}
// there is no offical instructor for future term sites
String requestUserId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
// authorizerList is added by daisyf for v2.4
List<String> authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (authorizerList == null) {
authorizerList = new ArrayList();
}
if (requestUserId != null) {
authorizerList.add(requestUserId);
}
for (int j = 0; j < authorizerList.size(); j++) {
String requestId = (String) authorizerList.get(j);
if (!isFutureTerm) {
// To site quest account - the instructor of record's
if (requestId != null) {
try {
User instructor = UserDirectoryService
.getUserByEid(requestId); // v2.4 -daisyf
from = requestEmail;
to = instructor.getEmail();
headerTo = instructor.getEmail();
replyTo = requestEmail;
buf.append(rb.getString("java.hello") + " \n\n");
buf.append(rb.getString("java.receiv") + " "
+ sessionUserName + ", ");
buf.append(rb.getString("java.who") + "\n");
if (termExist) {
String dateString = term.getStartDate()
.toString();
String year = dateString.substring(dateString
.length() - 4);
buf.append(term.getTitle() + " " + year + "\n");
}
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections
.get(i);
buf.append(so.getTitle() + "(" + so.getEid()
+ ")" + so.getCategory() + "\n");
}
buf.append("\n" + rb.getString("java.sitetitle")
+ "\t" + title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id);
buf.append("\n\n" + rb.getString("java.according")
+ " " + sessionUserName + " "
+ rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou") + " "
+ sessionUserName + " "
+ rb.getString("java.assoc") + "\n\n");
buf.append(rb.getString("java.respond") + " "
+ sessionUserName
+ rb.getString("java.appoint") + "\n\n");
buf.append(rb.getString("java.thanks") + "\n");
buf.append(productionSiteName + " "
+ rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject,
content, headerTo, replyTo, null);
// email has been sent successfully
sendEmailToRequestee = true;
} catch (UserNotDefinedException ee) {
M_log.warn(ee.getMessage());
} // try
}
}
}
// To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to") + "\t\t" + productionSiteName
+ " " + rb.getString("java.supp") + "\n");
buf.append("\n" + rb.getString("java.from") + "\t"
+ sessionUserName + "\n");
if (request.equals("new")) {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitereq") + "\n");
} else {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitechreq") + "\n");
}
buf.append(rb.getString("java.date") + "\t" + local_date + " "
+ local_time + "\n\n");
if (request.equals("new")) {
buf.append(rb.getString("java.approval") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
} else {
buf.append(rb.getString("java.approval2") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
}
if (termExist) {
String dateString = term.getStartDate().toString();
String year = dateString.substring(dateString.length() - 4);
buf.append(term.getTitle() + " " + year);
}
if (cmRequestedSections != null && cmRequestedSections.size() > 1) {
buf.append(" " + rb.getString("java.forthese") + " "
+ cmRequestedSections.size() + " "
+ rb.getString("java.sections") + "\n\n");
} else {
buf.append(" " + rb.getString("java.forthis") + "\n\n");
}
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections.get(i);
buf.append(so.getTitle() + "(" + so.getEid() + ")"
+ so.getCategory() + "\n");
}
buf.append(rb.getString("java.name") + "\t" + sessionUserName
+ " (" + noEmailInIdAccountName + " " + cUser.getEid()
+ ")\n");
buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id + "\n");
buf.append(rb.getString("java.siteinstr") + "\n" + additional
+ "\n\n");
if (!isFutureTerm) {
if (sendEmailToRequestee) {
buf.append(rb.getString("java.authoriz") + " "
+ requestUserId + " " + rb.getString("java.asreq"));
} else {
buf.append(rb.getString("java.thesiteemail") + " "
+ requestUserId + " " + rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
// To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing") + " ");
buf.append(rb.getString("java.meantime") + "\n\n");
buf.append(rb.getString("java.copy") + "\n\n");
buf.append(content);
buf.append("\n" + rb.getString("java.wish") + " " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, List notifySites) {
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
// send emails
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term_name = ((AcademicSession) state
.getAttribute(STATE_TERM_SELECTED)).getEid();
}
String message_subject = rb.getString("java.official") + " "
+ UserDirectoryService.getCurrentUser().getDisplayName()
+ " " + rb.getString("java.for") + " " + term_name;
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String sender = UserDirectoryService.getCurrentUser()
.getDisplayName();
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
try {
userId = UserDirectoryService.getUserEid(userId);
} catch (UserNotDefinedException e) {
M_log.warn(this + rb.getString("user.notdefined") + " "
+ userId);
}
// To Support
from = UserDirectoryService.getCurrentUser().getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = UserDirectoryService.getCurrentUser().getEmail();
StringBuffer buf = new StringBuffer();
buf.append("\n" + rb.getString("java.fromwork") + " "
+ ServerConfigurationService.getServerName() + " "
+ rb.getString("java.supp") + ":\n\n");
buf.append(rb.getString("java.off") + " '" + title + "' (id " + id
+ "), " + rb.getString("java.wasset") + " ");
buf.append(sender + " (" + userId + ", "
+ rb.getString("java.email2") + " " + replyTo + ") ");
buf.append(rb.getString("java.on") + " " + local_date + " "
+ rb.getString("java.at") + " " + local_time + " ");
buf.append(rb.getString("java.for") + " " + term_name + ", ");
int nbr_sections = notifySites.size();
if (nbr_sections > 1) {
buf.append(rb.getString("java.withrost") + " "
+ Integer.toString(nbr_sections) + " "
+ rb.getString("java.sections") + "\n\n");
} else {
buf.append(" " + rb.getString("java.withrost2") + "\n\n");
}
for (int i = 0; i < nbr_sections; i++) {
String course = (String) notifySites.get(i);
buf.append(rb.getString("java.course2") + " " + course + "\n");
}
String content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
} // if
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request
* parameters to c
*/
public void doCancel_create(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters
* to c int index = Integer.valueOf(params.getString
* ("template-index")).intValue();
*/
public void doCancel(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if (currentIndex.equals("4")) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
} else if (currentIndex.equals("5")) {
// remove related state variables
removeAddParticipantContext(state);
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
} else if (currentIndex.equals("6")) {
state.removeAttribute(STATE_REMOVEABLE_USER_LIST);
} else if (currentIndex.equals("9")) {
state.removeAttribute(FORM_WILL_NOTIFY);
} else if (currentIndex.equals("17") || currentIndex.equals("16")) {
state.removeAttribute(FORM_WILL_NOTIFY);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("13") || currentIndex.equals("14")) {
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("15")) {
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("cancelIndex"));
removeEditToolState(state);
}
// htripath: added 'currentIndex.equals("45")' for import from file
// cancel
else if (currentIndex.equals("19") || currentIndex.equals("20")
|| currentIndex.equals("21") || currentIndex.equals("22")
|| currentIndex.equals("45")) {
// from adding participant pages
// remove related state variables
removeAddParticipantContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("23") || currentIndex.equals("24")) {
// from change global access
state.removeAttribute("form_joinable");
state.removeAttribute("form_joinerRole");
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
} else if (currentIndex.equals("7") || currentIndex.equals("25")) {
// from change role
removeChangeRoleContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
} else if (currentIndex.equals("3")) {
// from adding class
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if (currentIndex.equals("27") || currentIndex.equals("28")) {
// from import
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// worksite setup
if (getStateSite(state) == null) {
// in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} else if (currentIndex.equals("26")) {
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null) {
// from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
} else if (currentIndex.equals("37") || currentIndex.equals("44")) {
// cancel back to edit class view
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
removeAddClassContext(state);
}
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request
* parameters Pass parameter to actionForTemplate to request action for
* backward direction
*/
public void doMenu_customize(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns
* to the site list
*
*/
public void doBack_to_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
if (site != null) {
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
// restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) {
state.setAttribute(STATE_PAGESIZE, state
.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_list
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doAdd_custom_link(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if ((params.getString("name")) == null
|| (params.getString("url") == null)) {
Tool tr = ToolManager.getTool("sakai.iframe");
Site site = getStateSite(state);
SitePage page = site.addPage();
page.setTitle(params.getString("name")); // the visible label on
// the tool menu
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", tr);
tool.setTitle(params.getString("name"));
commitSite(site);
} else {
addAlert(state, rb.getString("java.reqmiss"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
}
} // doAdd_custom_link
/**
* doAdd_remove_features is called when Make These Changes is clicked in
* chef_site-addRemoveFeatures
*/
public void doAdd_remove_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List existTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("addNews")) {
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES,
NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL,
Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else if (option.equalsIgnoreCase("addWC")) {
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES,
WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS,
WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params
.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else if (option.equalsIgnoreCase("save")) {
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's & titles of
// chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals(HOME_TOOL_ID)) {
homeSelected = true;
} else if (toolId.equals("sakai.mailbox")
|| toolId.indexOf("sakai.news") != -1
|| toolId.indexOf("sakai.iframe") != -1) {
// if user is adding either EmailArchive tool, News tool
// or Web Content tool, go to the Customize page for the
// tool
if (!existTools.contains(toolId)) {
goToENWPage = true;
}
if (toolId.equals("sakai.mailbox")) {
// get the email alias when an Email Archive tool
// has been selected
String channelReference = mailArchiveChannelReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List aliases = AliasService.getAliases(
channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS,
((Alias) aliases.get(0)).getId());
}
}
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(
homeSelected));
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST,
idsSelected); // List of ToolRegistration toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (goToENWPage) {
// go to the configuration page for Email Archive, News and
// Web Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to confirmation page
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}
}
} else if (option.equalsIgnoreCase("continue")) {
// continue
doContinue(data);
} else if (option.equalsIgnoreCase("Back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("Cancel")) {
// cancel
doCancel(data);
}
} // doAdd_remove_features
/**
* doSave_revised_features
*/
public void doSave_revised_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
getRevisedFeatures(params, state);
Site site = getStateSite(state);
String id = site.getId();
// now that the site exists, we can set the email alias when an Email
// Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias + " "
+ rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
// refresh the whole page
scheduleTopRefresh();
} // doSave_revised_features
/**
* doMenu_add_participant
*/
public void doMenu_add_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} // doMenu_add_participant
/**
* doMenu_siteInfo_addParticipant
*/
public void doMenu_siteInfo_addParticipant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
} // doMenu_siteInfo_addParticipant
/**
* doMenu_siteInfo_removeParticipant
*/
public void doMenu_siteInfo_removeParticipant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedUser") == null) {
addAlert(state, rb.getString("java.nousers"));
} else {
List removeUser = Arrays.asList(params.getStrings("selectedUser"));
// all or some selected user(s) can be removed, go to confirmation
// page
if (removeUser.size() > 0) {
state.setAttribute(STATE_TEMPLATE_INDEX, "6");
} else {
addAlert(state, rb.getString("java.however"));
}
state.setAttribute(STATE_REMOVEABLE_USER_LIST, removeUser);
}
} // doMenu_siteInfo_removeParticipant
/**
* doMenu_siteInfo_changeRole
*/
public void doMenu_siteInfo_changeRole(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedUser") == null) {
state.removeAttribute(STATE_SELECTED_USER_LIST);
addAlert(state, rb.getString("java.nousers2"));
} else {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
List selectedUserIds = Arrays.asList(params
.getStrings("selectedUser"));
state.setAttribute(STATE_SELECTED_USER_LIST, selectedUserIds);
// get roles for selected participants
setSelectedParticipantRoles(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "7");
}
}
} // doMenu_siteInfo_changeRole
/**
* doMenu_siteInfo_globalAccess
*/
public void doMenu_siteInfo_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "23");
}
} // doMenu_siteInfo_globalAccess
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID);
state
.setAttribute(STATE_TERM_SELECTED, cms
.getAcademicSession(termEid));
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* first step of adding class
*/
public void doAdd_class_select(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change")) {
// change term
String termId = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
} else if (option.equalsIgnoreCase("cancel")) {
// cancel
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} else if (option.equalsIgnoreCase("add")) {
String userId = UserDirectoryService.getCurrentUser().getEid();
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
if (t != null) {
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
// future term? roster information is not available yet?
int weeks = 0;
try {
weeks = Integer.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
} catch (Exception ignore) {
M_log.warn(ignore.getMessage());
}
if ((courses == null || courses != null && courses.size() == 0)
&& System.currentTimeMillis() + weeks * 7 * 24 * 60
* 60 * 1000 < t.getStartDate().getTime()) {
// if a future term is selected
state
.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
}
// continue
doContinue(data);
}
} // doAdd_class_select
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_change_roles
*/
public void doMenu_change_roles(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("removeUser") != null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new ArrayList(Arrays
.asList(params.getStrings("removeUser"))));
state.setAttribute(STATE_TEMPLATE_INDEX, "7");
} else {
addAlert(state, rb.getString("java.nousers2"));
}
} // doMenu_change_roles
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourceProperties siteProperties = Site.getProperties();
state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle());
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) {
state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf(
Site.isPubView()).toString());
}
state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription());
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site
.getShortDescription());
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
if (Site.getIconUrl() != null) {
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
}
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
String creatorId = siteProperties
.getProperty(ResourceProperties.PROP_CREATOR);
try {
User u = UserDirectoryService.getUser(creatorId);
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
} catch (UserNotDefinedException e) {
}
}
if (contactName != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
}
if (contactEmail != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* doMenu_publish_site
*
*/
public void doMenu_publish_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the site properties
sitePropertiesIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "9");
}
} // doMenu_publish_site
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
List titleEditableSiteType = (List) state
.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType())) {
Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE));
}
Site.setDescription((String) state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
Site.setShortDescription((String) state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
if (site_type != null) {
if (site_type.equals("course")) {
// set icon url for course
String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN);
setAppearance(state, Site, skin);
} else {
// set icon url for others
String iconUrl = (String) state
.getAttribute(FORM_SITEINFO_ICON_URL);
Site.setIconUrl(iconUrl);
}
}
// site contact information
String contactName = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_NAME);
if (contactName != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL);
if (contactEmail != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(Site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.removeAttribute(FORM_SITEINFO_CONTACT_NAME);
state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL);
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// refresh the whole page
scheduleTopRefresh();
}
} // doSave_siteInfo
/**
* init
*
*/
private void init(VelocityPortlet portlet, RunData data, SessionState state) {
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) {
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, new Integer(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null) {
PortletConfig config = portlet.getPortletConfig();
// all site types
String t = StringUtil.trimToNull(config
.getInitParameter("siteTypes"));
if (t != null) {
state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays
.asList(t.split(","))));
} else {
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
} // init
public void doNavigate_to_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = StringUtil.trimToNull(data.getParameters().getString(
"option"));
if (siteId != null) {
getReviseSite(state, siteId);
} else {
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId) {
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try {
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null) {
int pos = -1;
for (int index = 0; index < sites.size() && pos == -1; index++) {
if (((Site) sites.get(index)).getId().equals(siteId)) {
pos = index;
}
}
// has any previous site in the list?
if (pos > 0) {
state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1));
} else {
state.removeAttribute(STATE_PREV_SITE);
}
// has any next site in the list?
if (pos < sites.size() - 1) {
state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1));
} else {
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null) {
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
} catch (IdUnusedException e) {
M_log.warn(this + e.toString());
}
// one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService.allowUpdateSiteMembership(s.getId())) {
try {
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
// does the site has maintain type user(s) before updating
// participants?
String maintainRoleString = realmEdit.getMaintainRole();
boolean hadMaintainUser = !realmEdit.getUsersHasRole(
maintainRoleString).isEmpty();
// update participant roles
List participants = (List) state
.getAttribute(STATE_PARTICIPANT_LIST);
;
// remove all roles and then add back those that were checked
for (int i = 0; i < participants.size(); i++) {
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null) {
// get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
// only change roles when they are different than before
if (roleId != null) {
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null) {
activeGrant = params
.getString(activeGrantField)
.equalsIgnoreCase("true") ? true
: false;
}
boolean fromProvider = !participant.isRemoveable();
if (fromProvider && !roleId.equals(participant.getRole())) {
fromProvider = false;
}
realmEdit.addMember(id, roleId, activeGrant,
fromProvider);
}
}
}
// remove selected users
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params
.getStrings("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
try {
User user = UserDirectoryService.getUser(rId);
Participant selected = new Participant();
selected.name = user.getDisplayName();
selected.uniqname = user.getId();
realmEdit.removeMember(user.getId());
} catch (UserNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + rId
+ ". ");
}
}
}
if (hadMaintainUser
&& realmEdit.getUsersHasRole(maintainRoleString)
.isEmpty()) {
// if after update, the "had maintain type user" status
// changed, show alert message and don't save the update
addAlert(state, rb
.getString("sitegen.siteinfolist.nomaintainuser")
+ maintainRoleString + ".");
} else {
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false));
AuthzGroupService.save(realmEdit);
}
} catch (GroupNotDefinedException e) {
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + " IdUnusedException " + s.getTitle() + "("
+ realmId + "). ");
} catch (AuthzPermissionException e) {
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + " PermissionException " + s.getTitle() + "("
+ realmId + "). ");
}
}
} // doUpdate_participant
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters();
String publishUnpublish = params.getString("publishunpublish");
String include = params.getString("include");
String joinable = params.getString("joinable");
if (sEdit != null) {
// editing existing site
// publish site or not
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
sEdit.setPublished(true);
} else {
sEdit.setPublished(false);
}
// site public choice
if (include != null) {
// if there is pubview input, use it
sEdit.setPubView(include.equalsIgnoreCase("true") ? true
: false);
} else if (state.getAttribute(STATE_SITE_TYPE) != null) {
String type = (String) state.getAttribute(STATE_SITE_TYPE);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
sEdit.setPubView(true);
} else if (privateSiteTypes.contains(type)) {
// site are always private
sEdit.setPubView(false);
}
} else {
sEdit.setPubView(false);
}
// publish site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
state.setAttribute(STATE_JOINABLE, Boolean.TRUE);
sEdit.setJoinable(true);
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
state.setAttribute(STATE_JOINERROLE, joinerRole);
sEdit.setJoinerRole(joinerRole);
} else {
state.setAttribute(STATE_JOINERROLE, "");
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
state.setAttribute(STATE_JOINABLE, Boolean.FALSE);
state.removeAttribute(STATE_JOINERROLE);
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
}
} else {
// adding new site
if (state.getAttribute(STATE_SITE_INFO) != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
siteInfo.published = true;
} else {
siteInfo.published = false;
}
// site public choice
if (include != null) {
siteInfo.include = include.equalsIgnoreCase("true") ? true
: false;
} else if (StringUtil.trimToNull(siteInfo.site_type) != null) {
String type = StringUtil.trimToNull(siteInfo.site_type);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
siteInfo.include = true;
} else if (privateSiteTypes.contains(type)) {
// site are always private
siteInfo.include = false;
}
} else {
siteInfo.include = false;
}
// joinable site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
siteInfo.joinable = true;
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
siteInfo.joinerRole = joinerRole;
} else {
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
updateCurrentStep(state, true);
}
}
// if editing an existing site, refresh the whole page so that the
// publish/unpublish icon could be updated
if (sEdit != null) {
scheduleTopRefresh();
}
} // doUpdate_site_access
/**
* remove related state variable for changing participants roles
*
* @param state
* SessionState object
*/
private void removeChangeRoleContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeChangeRoleContext
/**
* /* Actions for vm templates under the "chef_site" root. This method is
* called by doContinue. Each template has a hidden field with the value of
* template-index that becomes the value of index for the switch statement
* here. Some cases not implemented.
*/
private void actionForTemplate(String direction, int index,
ParameterParser params, SessionState state) {
// Continue - make any permanent changes, Back - keep any data entered
// on the form
boolean forward = direction.equals("continue") ? true : false;
SiteInfo siteInfo = new SiteInfo();
switch (index) {
case 0:
/*
* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/*
* actionForTemplate chef_site-type.vm
*
*/
break;
case 2:
/*
* actionForTemplate chef_site-newSiteInformation.vm
*
*/
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// defaults to be true
siteInfo.include = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
updateSiteInfo(params, state);
// alerts after clicking Continue but not Back
if (forward) {
if (StringUtil.trimToNull(siteInfo.title) == null) {
addAlert(state, rb.getString("java.reqfields"));
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
return;
}
}
updateSiteAttributes(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 3:
/*
* actionForTemplate chef_site-newSiteFeatures.vm
*
*/
if (forward) {
getFeatures(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 4:
/*
* actionForTemplate chef_site-addRemoveFeature.vm
*
*/
break;
case 5:
/*
* actionForTemplate chef_site-addParticipant.vm
*
*/
if (forward) {
checkAddParticipant(params, state);
} else {
// remove related state variables
removeAddParticipantContext(state);
}
break;
case 6:
/*
* actionForTemplate chef_site-removeParticipants.vm
*
*/
break;
case 7:
/*
* actionForTemplate chef_site-changeRoles.vm
*
*/
if (forward) {
if (!((Boolean) state.getAttribute(STATE_CHANGEROLE_SAMEROLE))
.booleanValue()) {
getSelectedRoles(state, params, STATE_SELECTED_USER_LIST);
} else {
String role = params.getString("role_to_all");
if (role == null) {
addAlert(state, rb.getString("java.pleasechoose") + " ");
} else {
state
.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE,
role);
}
}
} else {
removeChangeRoleContext(state);
}
break;
case 8:
/*
* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 9:
/*
* actionForTemplate chef_site-publishUnpublish.vm
*
*/
updateSiteInfo(params, state);
break;
case 10:
/*
* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
break;
case 11:
/*
* actionForTemplate chef_site_newsitePublishUnpublish.vm
*
*/
break;
case 12:
/*
* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/*
* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward) {
Site Site = getStateSite(state);
List titleEditableSiteType = (List) state
.getAttribute(TITLE_EDITABLE_SITE_TYPE);
if (titleEditableSiteType.contains(Site.getType())) {
// site titel is editable and could not be null
String title = StringUtil.trimToNull(params
.getString("title"));
state.setAttribute(FORM_SITEINFO_TITLE, title);
if (title == null) {
addAlert(state, rb.getString("java.specify") + " ");
}
}
String description = StringUtil.trimToNull(params
.getString("description"));
state.setAttribute(FORM_SITEINFO_DESCRIPTION, description);
String short_description = StringUtil.trimToNull(params
.getString("short_description"));
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION,
short_description);
String skin = params.getString("skin");
if (skin != null) {
// if there is a skin input for course site
skin = StringUtil.trimToNull(skin);
state.setAttribute(FORM_SITEINFO_SKIN, skin);
} else {
// if ther is a icon input for non-course site
String icon = StringUtil.trimToNull(params
.getString("icon"));
if (icon != null) {
if (icon.endsWith(PROTOCOL_STRING)) {
addAlert(state, rb.getString("alert.protocol"));
}
state.setAttribute(FORM_SITEINFO_ICON_URL, icon);
} else {
state.removeAttribute(FORM_SITEINFO_ICON_URL);
}
}
// site contact information
String contactName = StringUtil.trimToZero(params
.getString("siteContactName"));
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "14");
}
}
break;
case 14:
/*
* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/*
* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 16:
/*
* actionForTemplate
* chef_site_siteInfo-publishUnpublish-sendEmail.vm
*
*/
if (forward) {
String notify = params.getString("notify");
if (notify != null) {
state.setAttribute(FORM_WILL_NOTIFY, new Boolean(notify));
}
}
break;
case 17:
/*
* actionForTemplate chef_site_siteInfo--publishUnpublish-confirm.vm
*
*/
if (forward) {
boolean oldStatus = getStateSite(state).isPublished();
boolean newStatus = ((SiteInfo) state
.getAttribute(STATE_SITE_INFO)).getPublished();
saveSiteStatus(state, newStatus);
if (oldStatus == false || newStatus == true) {
// if site's status been changed from unpublish to publish
// and notification is selected, send out notification to
// participants.
if (((Boolean) state.getAttribute(FORM_WILL_NOTIFY))
.booleanValue()) {
// %%% place holder for sending email
}
}
// commit site edit
Site site = getStateSite(state);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
}
break;
case 18:
/*
* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
case 19:
/*
* actionForTemplate chef_site-addParticipant-sameRole.vm
*
*/
String roleId = StringUtil.trimToNull(params
.getString("selectRole"));
if (roleId == null && forward) {
addAlert(state, rb.getString("java.pleasesel") + " ");
} else {
state.setAttribute("form_selectedRole", params
.getString("selectRole"));
}
break;
case 20:
/*
* actionForTemplate chef_site-addParticipant-differentRole.vm
*
*/
if (forward) {
getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS);
}
break;
case 21:
/*
* actionForTemplate chef_site-addParticipant-notification.vm '
*/
if (params.getString("notify") == null) {
if (forward)
addAlert(state, rb.getString("java.pleasechoice") + " ");
} else {
state.setAttribute("form_selectedNotify", new Boolean(params
.getString("notify")));
}
break;
case 22:
/*
* actionForTemplate chef_site-addParticipant-confirm.vm
*
*/
break;
case 23:
/*
* actionForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
if (forward) {
String joinable = params.getString("joinable");
state.setAttribute("form_joinable", Boolean.valueOf(joinable));
String joinerRole = params.getString("joinerRole");
state.setAttribute("form_joinerRole", joinerRole);
if (joinable.equals("true")) {
if (joinerRole == null) {
addAlert(state, rb.getString("java.pleasesel") + " ");
}
}
} else {
}
break;
case 24:
/*
* actionForTemplate
* chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 25:
/*
* actionForTemplate chef_site-changeRoles-confirm.vm
*
*/
break;
case 26:
/*
* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, forward);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 27:
/*
* actionForTemplate chef_site-importSites.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
importToolIntoSite(selectedTools, importTools,
existingSite);
existingSite = getStateSite(state); // refresh site for
// WC and News
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(existingSite);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 28:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/*
* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward) {
if (state.getAttribute(SITE_DUPLICATED) == null) {
if (StringUtil.trimToNull(params.getString("title")) == null) {
addAlert(state, rb.getString("java.dupli") + " ");
} else {
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
try {
String oSiteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String nSiteId = IdManager.createUuid();
Site site = SiteService.addSite(nSiteId,
getStateSite(state));
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
try {
site = SiteService.getSite(nSiteId);
// set title
site.setTitle(title);
// import tool content
List pageList = site.getPages();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
String toolId = ((ToolConfiguration) pageToolList
.get(0)).getTool().getId();
if (toolId
.equalsIgnoreCase("sakai.resources")) {
// handle
// resource
// tool
// specially
transferCopyEntities(
toolId,
ContentHostingService
.getSiteCollection(oSiteId),
ContentHostingService
.getSiteCollection(nSiteId));
} else {
// other
// tools
transferCopyEntities(toolId,
oSiteId, nSiteId);
}
}
}
} catch (Exception e1) {
// if goes here, IdService
// or SiteService has done
// something wrong.
M_log.warn(this + "Exception" + e1 + ":"
+ nSiteId + "when duplicating site");
}
if (site.getType().equals("course")) {
// for course site, need to
// read in the input for
// term information
String termId = StringUtil.trimToNull(params
.getString("selectTerm"));
if (termId != null) {
site.getPropertiesEdit().addProperty(
PROP_SITE_TERM, termId);
}
}
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// TODO: hard coding this frame id
// is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.siteinval"));
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitebeenused")
+ " ");
} catch (PermissionException e) {
addAlert(state, rb.getString("java.allowcreate")
+ " ");
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward) {
List providerChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null) {
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (params.getString("manualAdds") == null) {
addAlert(state, rb.getString("java.manual") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null) {
providerChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAdd"))); // list of
// course
// ids
String userId = (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED);
String currentUserId = (String) state
.getAttribute(STATE_CM_CURRENT_USERID);
if (userId == null
|| (userId != null && userId
.equals(currentUserId))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
} else {
// STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
// so need to prepare it
// also in this page, u can pick either section from
// current user OR
// sections from another users but not both. -
// daisy's note 1 for now
// till we are ready to add more complexity
List sectionObjectList = prepareSectionObject(
providerChosenList, userId);
state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS,
sectionObjectList);
state
.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// set special instruction & we will keep
// STATE_CM_AUTHORIZER_LIST
String additional = StringUtil.trimToZero(params
.getString("additional"));
state.setAttribute(FORM_ADDITIONAL, additional);
}
}
collectNewSiteInfo(siteInfo, state, params,
providerChosenList);
}
// next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
break;
case 52:
// v2.4 - added by daisyf
// RemoveSection - remove any selected course from a list of
// provider courses
// check if any section need to be removed
removeAnyFlagedSection(state, params);
List providerChosenList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
collectNewSiteInfo(siteInfo, state, params, providerChosenList);
// next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
break;
case 38:
break;
case 39:
break;
case 42:
/*
* actionForTemplate chef_site-gradtoolsConfirm.vm
*
*/
break;
case 43:
/*
* actionForTemplate chef_site-editClass.vm
*
*/
if (forward) {
if (params.getStrings("providerClassDeletes") == null
&& params.getStrings("manualClassDeletes") == null
&& !direction.equals("back")) {
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null) {
// build the deletions list
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList
.listIterator(); i.hasNext();) {
providerCourseList.remove((String) i.next());
}
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null) {
// build the deletions list
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i
.hasNext();) {
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
}
updateCourseClasses(state, new Vector(), new Vector());
}
break;
case 44:
if (forward) {
List providerList = (state
.getAttribute(SITE_PROVIDER_COURSE_LIST) == null) ? new Vector()
: (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List addProviderList = (state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) == null) ? new Vector()
: (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
providerList.addAll(addProviderList);
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerList);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
// if manually added course
List manualList = (state
.getAttribute(SITE_MANUAL_COURSE_LIST) == null) ? new Vector()
: (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
int manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
List manualAddFields = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
AcademicSession a = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
for (int m = 0; m < manualAddNumber && a != null; m++) {
String manualAddClassId = sectionFieldProvider
.getSectionEid(a.getEid(),
(List) manualAddFields.get(m));
manualList.add(manualAddClassId);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST, manualList);
}
updateCourseClasses(state, (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN),
(List) state.getAttribute(SITE_MANUAL_COURSE_LIST));
removeAddClassContext(state);
}
break;
case 49:
if (!forward) {
state.removeAttribute(SORTED_BY);
state.removeAttribute(SORTED_ASC);
}
break;
}
}// actionFor Template
/**
* update current step index within the site creation wizard
*
* @param state
* The SessionState object
* @param forward
* Moving forward or backward?
*/
private void updateCurrentStep(SessionState state, boolean forward) {
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
int currentStep = ((Integer) state
.getAttribute(SITE_CREATE_CURRENT_STEP)).intValue();
if (forward) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep + 1));
} else {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep - 1));
}
}
}
/**
* remove related state variable for adding class
*
* @param state
* SessionState object
*/
private void removeAddClassContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} // removeAddClassContext
private void updateCourseClasses(SessionState state, List notifyClasses,
List requestClasses) {
List providerCourseSectionList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null)
|| (providerCourseSectionList.size() == 0)) {
// no section access so remove Provider Id
try {
AuthzGroup realmEdit1 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotedit"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null)
&& (providerCourseSectionList.size() != 0)) {
// section access so rewrite Provider Id
String externalRealm = buildExternalRealm(id, state,
providerCourseSectionList);
try {
AuthzGroup realmEdit2 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotclasses"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((manualCourseSectionList != null)
&& (manualCourseSectionList.size() != 0)) {
// store the manually requested sections in one site property
String manualSections = "";
for (int j = 0; j < manualCourseSectionList.size();) {
manualSections = manualSections
+ (String) manualCourseSectionList.get(j);
j++;
if (j < manualCourseSectionList.size()) {
manualSections = manualSections + "+";
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
} else {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(PROP_SITE_REQUEST_COURSE);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(site);
} else {
}
if (requestClasses != null && requestClasses.size() > 0
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
try {
// send out class request notifications
sendSiteRequest(state, "change", ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue(), (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
if (notifyClasses != null && notifyClasses.size() > 0) {
try {
// send out class access confirmation notifications
sendSiteNotification(state, notifyClasses);
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
} // updateCourseClasses
/**
* Sets selected roles for multiple users
*
* @param params
* The ParameterParser object
* @param listName
* The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params,
String listName) {
Hashtable pSelectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null) {
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++) {
String userId = null;
if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) {
userId = ((Participant) userList.get(i)).getUniqname();
} else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) {
userId = (String) userList.get(i);
}
if (userId != null) {
String rId = StringUtil.trimToNull(params.getString("role"
+ userId));
if (rId == null) {
addAlert(state, rb.getString("java.rolefor") + " " + userId
+ ". ");
pSelectedRoles.remove(userId);
} else {
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params
.getString("role_to_all"));
} else if (option.equalsIgnoreCase("same_role_false")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) {
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
new Hashtable());
}
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* dispatch function for changing site global access
*/
public void doSiteinfo_edit_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("joinable")) {
state.setAttribute("form_joinable", Boolean.TRUE);
state.setAttribute("form_joinerRole", getStateSite(state)
.getJoinerRole());
} else if (option.equalsIgnoreCase("unjoinable")) {
state.setAttribute("form_joinable", Boolean.FALSE);
state.removeAttribute("form_joinerRole");
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable"))
.booleanValue();
s.setJoinable(joinable);
if (joinable) {
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes(SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
M_log
.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null) {
if (StringUtil.trimToNull(siteInfo.title) != null) {
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null) {
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtil.trimToNull(siteInfo.joinerRole) != null) {
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
if (SiteService.allowUpdateSite(id)) {
try {
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
} catch (IdUnusedException e) {
M_log.warn("SiteAction.commitSite IdUnusedException "
+ siteInfo.getTitle() + "(" + id + ") not found");
}
}
// no permission
else {
addAlert(state, rb.getString("java.makechanges"));
M_log.warn("SiteAction.commitSite PermissionException "
+ siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo(ParameterParser params, SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (params.getString("title") != null) {
siteInfo.title = params.getString("title");
}
if (params.getString("description") != null) {
siteInfo.description = params.getString("description");
}
if (params.getString("short_description") != null) {
siteInfo.short_description = params.getString("short_description");
}
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
if (params.getString("iconUrl") != null) {
siteInfo.iconUrl = params.getString("iconUrl");
} else {
siteInfo.iconUrl = params.getString("skin");
}
if (params.getString("joinerRole") != null) {
siteInfo.joinerRole = params.getString("joinerRole");
}
if (params.getString("joinable") != null) {
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if (!joinable)
siteInfo.joinerRole = NULL_STRING;
}
if (params.getString("itemStatus") != null) {
siteInfo.published = Boolean
.valueOf(params.getString("itemStatus")).booleanValue();
}
// site contact information
String name = StringUtil
.trimToZero(params.getString("siteContactName"));
siteInfo.site_contact_name = name;
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
if (email != null) {
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
siteInfo.site_contact_email = email;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
/**
* getExternalRealmId
*
*/
private String getExternalRealmId(SessionState state) {
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
String rv = null;
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getExternalRealmId, site realm not found");
}
return rv;
} // getExternalRealmId
/**
* getParticipantList
*
*/
private List getParticipantList(SessionState state) {
List members = new Vector();
List participants = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List providerCourseList = null;
providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
participants = prepareParticipants(realmId, providerCourseList);
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
private Vector prepareParticipants(String realmId, List providerCourseList) {
Vector participants = new Vector();
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
realm.getProviderGroupId();
// iterate through the provider list first
for (Iterator i=providerCourseList.iterator(); i.hasNext();)
{
String providerCourseEid = (String) i.next();
Set enrollmentSet = cms.getEnrollments(providerCourseEid);
for (Iterator eIterator = enrollmentSet.iterator();eIterator.hasNext();)
{
Enrollment e = (Enrollment) eIterator.next();
try
{
User user = UserDirectoryService.getUserByEid(e.getUserId());
Member member = realm.getMember(user.getId());
if (member != null && member.isProvided())
{
// add provided participant
Participant participant = new Participant();
participant.credits = e.getCredits();
participant.name = user.getSortName();
participant.providerRole = member.getRole()!=null?member.getRole().getId():"";
participant.regId = "";
participant.removeable = false;
participant.role = member.getRole()!=null?member.getRole().getId():"";
participant.section = cms.getSection(providerCourseEid).getTitle();
participant.uniqname = user.getId();
participants.add(participant);
}
} catch (UserNotDefinedException exception) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(exception.getMessage());
}
}
}
// now for those not provided users
Set grants = realm.getMembers();
for (Iterator i = grants.iterator(); i.hasNext();) {
Member g = (Member) i.next();
if (!g.isProvided())
{
try {
User user = UserDirectoryService.getUserByEid(g.getUserEid());
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
participant.role = g.getRole()!=null?g.getRole().getId():"";
participant.removeable = true;
participants.add(participant);
} catch (UserNotDefinedException e) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(e.getMessage());
}
}
}
} catch (GroupNotDefinedException ee) {
M_log.warn(this + " IdUnusedException " + realmId);
}
return participants;
}
/**
* getRoles
*
*/
private List getRoles(SessionState state) {
List roles = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getRoles IdUnusedException " + realmId);
}
return roles;
} // getRoles
private void addSynopticTool(SitePage page, String toolId,
String toolTitle, String layoutHint) {
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
}
private void getRevisedFeatures(ParameterParser params, SessionState state) {
Site site = getStateSite(state);
// get the list of Worksite Setup configured pages
List wSetupPageList = (List) state
.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
// declare some flags used in making decisions about Home, whether to
// add, remove, or do nothing
boolean homeInChosenList = false;
boolean homeInWSetupPageList = false;
List chosenList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// if features were selected, diff wSetupPageList and chosenList to get
// page adds and removes
// boolean values for adding synoptic views
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasEmail = false;
boolean hasNewSiteInfo = false;
// Special case - Worksite Setup Home comes from a hardcoded checkbox on
// the vm template rather than toolRegistrationList
// see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String choice = (String) j.next();
if (choice.equalsIgnoreCase(HOME_TOOL_ID)) {
homeInChosenList = true;
} else if (choice.equals("sakai.mailbox")) {
hasEmail = true;
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
if (!Validator.checkEmailLocal(alias)) {
addAlert(state, rb.getString("java.theemail"));
} else {
try {
String channelReference = mailArchiveChannelReference(site
.getId());
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check
// to
// see
// whether
// the
// alias
// has
// been
// used
try {
String target = AliasService.getTarget(alias);
if (target != null) {
addAlert(state, rb
.getString("java.emailinuse")
+ " ");
}
} catch (IdUnusedException ee) {
try {
AliasService.setAlias(alias,
channelReference);
} catch (IdUsedException exception) {
} catch (IdInvalidException exception) {
} catch (PermissionException exception) {
}
}
} catch (PermissionException exception) {
}
}
}
} else if (choice.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (choice.equals("sakai.schedule")) {
hasSchedule = true;
} else if (choice.equals("sakai.chat")) {
hasChat = true;
} else if (choice.equals("sakai.discussion")) {
hasDiscussion = true;
}
}
// see if Home and/or Help in the wSetupPageList (can just check title
// here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
wSetupPage = (WorksiteSetupPage) i.next();
if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) {
homeInWSetupPageList = true;
}
}
if (homeInChosenList) {
SitePage page = null;
// Were the synoptic views of Announcement, Discussioin, Chat
// existing before the editing
boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false;
if (homeInWSetupPageList) {
if (!SiteService.isUserSite(site.getId())) {
// for non-myworkspace site, if Home is chosen and Home is
// in the wSetupPageList, remove synoptic tools
WorksiteSetupPage homePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i
.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i
.next();
if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) {
homePage = comparePage;
}
}
page = site.getPage(homePage.getPageId());
List toolList = page.getTools();
List removeToolList = new Vector();
// get those synoptic tools
for (ListIterator iToolList = toolList.listIterator(); iToolList
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) iToolList
.next();
if (tool.getTool().getId().equals(
"sakai.synoptic.announcement")) {
hadAnnouncement = true;
if (!hasAnnouncement) {
removeToolList.add(tool);// if Announcement
// tool isn't
// selected, remove
// the synotic
// Announcement
}
}
if (tool.getTool().getId().equals(
TOOL_ID_SUMMARY_CALENDAR)) {
hadSchedule = true;
if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule
removeToolList.add(tool);
}
}
if (tool.getTool().getId().equals(
"sakai.synoptic.discussion")) {
hadDiscussion = true;
if (!hasDiscussion) {
removeToolList.add(tool);// if Discussion
// tool isn't
// selected, remove
// the synoptic
// Discussion
}
}
if (tool.getTool().getId()
.equals("sakai.synoptic.chat")) {
hadChat = true;
if (!hasChat) {
removeToolList.add(tool);// if Chat tool
// isn't selected,
// remove the
// synoptic Chat
}
}
}
// remove those synoptic tools
for (ListIterator rToolList = removeToolList.listIterator(); rToolList
.hasNext();) {
page.removeTool((ToolConfiguration) rToolList.next());
}
}
} else {
// if Home is chosen and Home is not in wSetupPageList, add Home
// to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = HOME_TOOL_ID;
wSetupPageList.add(wSetupHome);
// Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", reg);
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
}
if (!SiteService.isUserSite(site.getId())) {
// add synoptical tools to home tool in non-myworkspace site
try {
if (hasAnnouncement && !hadAnnouncement) {
// Add synoptic announcements tool
addSynopticTool(page, "sakai.synoptic.announcement", rb
.getString("java.recann"), "0,1");
}
if (hasDiscussion && !hadDiscussion) {
// Add synoptic discussion tool
addSynopticTool(page, "sakai.synoptic.discussion", rb
.getString("java.recdisc"), "1,1");
}
if (hasChat && !hadChat) {
// Add synoptic chat tool
addSynopticTool(page, "sakai.synoptic.chat", rb
.getString("java.recent"), "2,1");
}
if (hasSchedule && !hadSchedule) {
// Add synoptic schedule tool if not stealth or hidden
if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR))
addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb
.getString("java.reccal"), "3,1");
}
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
} catch (Exception e) {
M_log.warn("SiteAction.getFeatures Exception "
+ e.getMessage());
}
}
} // add Home
// if Home is in wSetupPageList and not chosen, remove Home feature from
// wSetupPageList and site
if (!homeInChosenList && homeInWSetupPageList) {
// remove Home from wSetupPageList
WorksiteSetupPage removePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if (comparePage.getToolId().equals(HOME_TOOL_ID)) {
removePage = comparePage;
}
}
SitePage siteHome = site.getPage(removePage.getPageId());
site.removePage(siteHome);
wSetupPageList.remove(removePage);
}
// declare flags used in making decisions about whether to add, remove,
// or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Hashtable newsTitles = (Hashtable) state
.getAttribute(STATE_NEWS_TITLES);
Hashtable wcTitles = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcUrls = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_URLS);
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1
|| pageToolId.indexOf("sakai.iframe") != -1) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (pageToolId.equals(toolId)) {
inChosenList = true;
}
}
if (!inChosenList) {
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++) {
// if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
if (!wSetupPage.getPageId().equals(removeId)) {
wSetupPage = null;
}
}
if (wSetupPage != null) {
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state,
(String) state.getAttribute(STATE_SITE_TYPE), chosenList)
.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
// Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple News and Web Content tool
if (pageToolId.indexOf("sakai.news") != -1
|| pageToolId.indexOf("sakai.iframe") != -1) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if (pageToolId.equals(toolId)) {
inWSetupPageList = true;
// but for News and Web Content tool, need to change the
// title
if (toolId.indexOf("sakai.news") != -1) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) newsTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
if (tool.getTool().getId().equals("sakai.news")) {
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
// set News tool url
String urlString = (String) newsUrls
.get(toolId);
try {
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty(
"channel-url",
(String) url.toExternalForm());
} catch (MalformedURLException e) {
addAlert(state, rb.getString("java.invurl")
+ " " + urlString + ". ");
}
}
}
} else if (toolId.indexOf("sakai.iframe") != -1) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) wcTitles.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
if (tool.getTool().getId().equals("sakai.iframe")) {
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil
.trimToNull((String) wcUrls.get(toolId));
if (wcUrl != null
&& !wcUrl
.equals(WEB_CONTENT_DEFAULT_URL)) {
// if url is not empty and not consists only
// of "http://"
tool.getPlacementConfig().setProperty(
"source", wcUrl);
}
}
}
}
}
}
if (inWSetupPageList) {
// if the tool already in the list, do nothing so to save the
// option settings
} else {
// if in chosen list but not in wSetupPageList, add it to the
// site (one tool on a page)
// if Site Info tool is being newly added
if (toolId.equals("sakai.siteinfo")) {
hasNewSiteInfo = true;
}
Tool toolRegFound = null;
for (Iterator i = toolRegistrationList.iterator(); i.hasNext();) {
Tool toolReg = (Tool) i.next();
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(toolReg.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(toolReg.getId()) != -1)) {
toolRegFound = toolReg;
}
}
if (toolRegFound != null) {
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (toolId.indexOf("sakai.news") != -1) {
// set News tool title
page.setTitle((String) newsTitles.get(toolId));
} else if (toolId.indexOf("sakai.iframe") != -1) {
// set Web Content tool title
page.setTitle((String) wcTitles.get(toolId));
} else {
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
// set tool title
if (toolId.indexOf("sakai.news") != -1) {
// set News tool title
tool.setTitle((String) newsTitles.get(toolId));
// set News tool url
String urlString = (String) newsUrls.get(toolId);
try {
URL url = new URL(urlString);
// update the tool config
tool.getPlacementConfig().setProperty(
"channel-url",
(String) url.toExternalForm());
} catch (MalformedURLException e) {
// display message
addAlert(state, "Invalid URL " + urlString + ". ");
// remove the page because of invalid url
site.removePage(page);
}
} else if (toolId.indexOf("sakai.iframe") != -1) {
// set Web Content tool title
tool.setTitle((String) wcTitles.get(toolId));
// set Web Content tool url
String wcUrl = StringUtil.trimToNull((String) wcUrls
.get(toolId));
if (wcUrl != null
&& !wcUrl.equals(WEB_CONTENT_DEFAULT_URL)) {
// if url is not empty and not consists only of
// "http://"
tool.getPlacementConfig().setProperty("source",
wcUrl);
}
} else {
tool.setTitle(toolRegFound.getTitle());
}
}
}
} // for
if (homeInChosenList) {
// Order tools - move Home to the top - first find it
SitePage homePage = null;
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if (rb.getString("java.home").equals(page.getTitle()))// if
// ("Home".equals(page.getTitle()))
{
homePage = page;
break;
}
}
}
// if found, move it
if (homePage != null) {
// move home from it's index to the first position
int homePosition = pageList.indexOf(homePage);
for (int n = 0; n < homePosition; n++) {
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasNewSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
}
// if there is no email tool chosen
if (!hasEmail) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
// commit
commitSite(site);
} // getRevisedFeatures
/**
* Is the tool stealthed or hidden
* @param toolId
* @return
*/
private boolean notStealthOrHiddenTool(String toolId) {
return (ToolManager.getTool(toolId) != null
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId)
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId));
}
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state) {
List idsSelected = new Vector();
boolean goToENWPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's & titles of
// chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals("sakai.mailbox")
|| toolId.indexOf("sakai.news") != -1
|| toolId.indexOf("sakai.iframe") != -1) {
goToENWPage = true;
} else if (toolId.equals(HOME_TOOL_ID)) {
homeSelected = true;
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(
homeSelected));
}
String importString = params.getString("import");
if (importString != null
&& importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null) {
importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
}
if (importSites.size() == 0) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
if (!sites.containsKey(s)) {
sites.put(s, new Vector());
}
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List
// of
// ToolRegistration
// toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_IMPORT) != null) {
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
} else if (goToENWPage) {
// go to the configuration page for Email Archive, News and Web
// Content tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to edit access page
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
int totalSteps = 4;
if (state.getAttribute(STATE_SITE_TYPE) != null
&& ((String) state.getAttribute(STATE_SITE_TYPE))
.equalsIgnoreCase("course")) {
totalSteps = 5;
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
totalSteps++;
}
}
if (state.getAttribute(STATE_IMPORT) != null) {
totalSteps++;
}
if (goToENWPage) {
totalSteps++;
}
state
.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(
totalSteps));
}
} // getFeatures
/**
* addFeatures adds features to a new site
*
*/
private void addFeatures(SessionState state) {
List toolRegistrationList = (Vector) state
.getAttribute(STATE_TOOL_REGISTRATION_LIST);
Site site = getStateSite(state);
List pageList = new Vector();
int moves = 0;
boolean hasHome = false;
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasSiteInfo = false;
List chosenList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) {
importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
}
// for tools other than home
if (chosenList.contains(HOME_TOOL_ID)) {
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, site.getType(), chosenList);
// titles for news tools
Hashtable newsTitles = (Hashtable) state
.getAttribute(STATE_NEWS_TITLES);
// urls for news tools
Hashtable newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
// titles for web content tools
Hashtable wcTitles = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES);
// urls for web content tools
Hashtable wcUrls = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_URLS);
if (chosenList.size() > 0) {
Tool toolRegFound = null;
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String toolId = (String) i.next();
// find the tool in the tool registration list
toolRegFound = null;
for (int j = 0; j < toolRegistrationList.size()
&& toolRegFound == null; j++) {
MyTool tool = (MyTool) toolRegistrationList.get(j);
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(tool.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(tool.getId()) != -1)) {
toolRegFound = ToolManager.getTool(tool.getId());
}
}
if (toolRegFound != null) {
if (toolId.indexOf("sakai.news") != -1) {
// adding multiple news tool
String newsTitle = (String) newsTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(newsTitle); // the visible label on the
// tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.news", ToolManager
.getTool("sakai.news"));
tool.setTitle(newsTitle);
tool.setLayoutHints("0,0");
String urlString = (String) newsUrls.get(toolId);
// update the tool config
tool.getPlacementConfig().setProperty("channel-url",
urlString);
} else if (toolId.indexOf("sakai.iframe") != -1) {
// adding multiple web content tool
String wcTitle = (String) wcTitles.get(toolId);
SitePage page = site.addPage();
page.setTitle(wcTitle); // the visible label on the tool
// menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", ToolManager
.getTool("sakai.iframe"));
tool.setTitle(wcTitle);
tool.setLayoutHints("0,0");
String wcUrl = StringUtil.trimToNull((String) wcUrls
.get(toolId));
if (wcUrl != null
&& !wcUrl.equals(WEB_CONTENT_DEFAULT_URL)) {
// if url is not empty and not consists only of
// "http://"
tool.getPlacementConfig().setProperty("source",
wcUrl);
}
} else {
SitePage page = site.addPage();
page.setTitle(toolRegFound.getTitle()); // the visible
// label on the
// tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
tool.setLayoutHints("0,0");
} // Other features
}
// booleans for synoptic views
if (toolId.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (toolId.equals("sakai.schedule")) {
hasSchedule = true;
} else if (toolId.equals("sakai.chat")) {
hasChat = true;
} else if (toolId.equals("sakai.discussion")) {
hasDiscussion = true;
} else if (toolId.equals("sakai.siteinfo")) {
hasSiteInfo = true;
}
} // for
// add home tool
if (hasHome) {
// Home is a special case, with several tools on the page.
// "home" is hard coded in chef_site-addRemoveFeatures.vm.
try {
SitePage page = site.addPage();
page.setTitle(rb.getString("java.home")); // the visible
// label on the
// tool menu
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
// Add worksite information tool
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe.site", ToolManager
.getTool("sakai.iframe.site"));
tool.setTitle(rb.getString("java.workinfo"));
tool.setLayoutHints("0,0");
if (hasAnnouncement) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.announcement", ToolManager
.getTool("sakai.synoptic.announcement"));
tool.setTitle(rb.getString("java.recann"));
tool.setLayoutHints("0,1");
}
if (hasDiscussion) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.discussion", ToolManager
.getTool("sakai.synoptic.discussion"));
tool.setTitle("Recent Discussion Items");
tool.setLayoutHints("1,1");
}
if (hasChat) {
// Add synoptic chat tool
tool = page.addTool();
tool.setTool("sakai.synoptic.chat", ToolManager
.getTool("sakai.synoptic.chat"));
tool.setTitle("Recent Chat Messages");
tool.setLayoutHints("2,1");
}
if (hasSchedule && notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// Add synoptic schedule tool
tool = page.addTool();
tool.setTool(TOOL_ID_SUMMARY_CALENDAR, ToolManager
.getTool(TOOL_ID_SUMMARY_CALENDAR));
tool.setTitle(rb.getString("java.reccal"));
tool.setLayoutHints("3,1");
}
} catch (Exception e) {
M_log.warn("SiteAction.getFeatures Exception "
+ e.getMessage());
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE);
// Order tools - move Home to the top
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if ((page.getTitle()).equals(rb.getString("java.home"))) {
moves = pageList.indexOf(page);
for (int n = 0; n < moves; n++) {
page.moveUp();
}
}
}
}
} // Home feature
// move Site Info tool, if selected, to the end of tool list
if (hasSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
} // Site Info
}
// commit
commitSite(site);
// import
importToolIntoSite(chosenList, importTools, site);
} // addFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = ContentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = ContentHostingService
.getSiteCollection(toSiteId);
transferCopyEntities(toolId, fromSiteCollectionId,
toSiteCollectionId);
resourcesImported = true;
}
}
}
// ijmport other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
transferCopyEntities(toolId, fromSiteId, toSiteId);
}
}
}
}
} // importToolIntoSite
public void saveSiteStatus(SessionState state, boolean published) {
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published) {
site.setPublished(published);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
} // commitSite
public void commitSite(Site site) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}// commitSite
private boolean isValidDomain(String email) {
String invalidEmailInIdAccountString = ServerConfigurationService
.getString("invalidEmailInIdAccountString", null);
if (invalidEmailInIdAccountString != null) {
String[] invalidDomains = invalidEmailInIdAccountString.split(",");
for (int i = 0; i < invalidDomains.length; i++) {
String domain = invalidDomains[i].trim();
if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) {
return false;
}
}
}
return true;
}
private void checkAddParticipant(ParameterParser params, SessionState state) {
// get the participants to be added
int i;
Vector pList = new Vector();
HashSet existingUsers = new HashSet();
Site site = null;
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
try {
site = SiteService.getSite(siteId);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("java.specif") + " " + siteId);
}
// accept noEmailInIdAccounts and/or emailInIdAccount account names
String noEmailInIdAccounts = "";
String emailInIdAccounts = "";
// check that there is something with which to work
noEmailInIdAccounts = StringUtil.trimToNull((params
.getString("noEmailInIdAccount")));
emailInIdAccounts = StringUtil.trimToNull(params
.getString("emailInIdAccount"));
state.setAttribute("noEmailInIdAccountValue", noEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue", emailInIdAccounts);
// if there is no uniquname or emailInIdAccount entered
if (noEmailInIdAccounts == null && emailInIdAccounts == null) {
addAlert(state, rb.getString("java.guest"));
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
return;
}
String at = "@";
if (noEmailInIdAccounts != null) {
// adding noEmailInIdAccounts
String[] noEmailInIdAccountArray = noEmailInIdAccounts
.split("\r\n");
for (i = 0; i < noEmailInIdAccountArray.length; i++) {
String noEmailInIdAccount = StringUtil
.trimToNull(noEmailInIdAccountArray[i].replaceAll(
"[\t\r\n]", ""));
// if there is some text, try to use it
if (noEmailInIdAccount != null) {
// automaticially add emailInIdAccount account
Participant participant = new Participant();
try {
User u = UserDirectoryService
.getUserByEid(noEmailInIdAccount);
if (site != null && site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be added
// again
existingUsers.add(noEmailInIdAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = noEmailInIdAccount;
pList.add(participant);
}
} catch (UserNotDefinedException e) {
addAlert(state, noEmailInIdAccount + " "
+ rb.getString("java.username") + " ");
}
}
}
} // noEmailInIdAccounts
if (emailInIdAccounts != null) {
String[] emailInIdAccountArray = emailInIdAccounts.split("\r\n");
for (i = 0; i < emailInIdAccountArray.length; i++) {
String emailInIdAccount = emailInIdAccountArray[i];
// if there is some text, try to use it
emailInIdAccount.replaceAll("[ \t\r\n]", "");
// remove the trailing dots and empty space
while (emailInIdAccount.endsWith(".")
|| emailInIdAccount.endsWith(" ")) {
emailInIdAccount = emailInIdAccount.substring(0,
emailInIdAccount.length() - 1);
}
if (emailInIdAccount != null && emailInIdAccount.length() > 0) {
String[] parts = emailInIdAccount.split(at);
if (emailInIdAccount.indexOf(at) == -1) {
// must be a valid email address
addAlert(state, emailInIdAccount + " "
+ rb.getString("java.emailaddress"));
} else if ((parts.length != 2) || (parts[0].length() == 0)) {
// must have both id and address part
addAlert(state, emailInIdAccount + " "
+ rb.getString("java.notemailid"));
} else if (!Validator.checkEmailLocal(parts[0])) {
addAlert(state, emailInIdAccount + " "
+ rb.getString("java.emailaddress")
+ rb.getString("java.theemail"));
} else if (emailInIdAccount != null
&& !isValidDomain(emailInIdAccount)) {
// wrong string inside emailInIdAccount id
addAlert(state, emailInIdAccount + " "
+ rb.getString("java.emailaddress") + " ");
} else {
Participant participant = new Participant();
try {
// if the emailInIdAccount user already exists
User u = UserDirectoryService
.getUserByEid(emailInIdAccount);
if (site != null
&& site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be
// added again
existingUsers.add(emailInIdAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = emailInIdAccount;
pList.add(participant);
}
} catch (UserNotDefinedException e) {
// if the emailInIdAccount user is not in the system
// yet
participant.name = emailInIdAccount;
participant.uniqname = emailInIdAccount; // TODO:
// what
// would
// the
// UDS
// case
// this
// name
// to?
// -ggolden
pList.add(participant);
}
}
} // if
} //
} // emailInIdAccounts
boolean same_role = true;
if (params.getString("same_role") == null) {
addAlert(state, rb.getString("java.roletype") + " ");
} else {
same_role = params.getString("same_role").equals("true") ? true
: false;
state.setAttribute("form_same_role", new Boolean(same_role));
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} else {
if (same_role) {
state.setAttribute(STATE_TEMPLATE_INDEX, "19");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "20");
}
}
// remove duplicate or existing user from participant list
pList = removeDuplicateParticipants(pList, state);
state.setAttribute(STATE_ADD_PARTICIPANTS, pList);
// if the add participant list is empty after above removal, stay in the
// current page
if (pList.size() == 0) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
// add alert for attempting to add existing site user(s)
if (!existingUsers.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator eIterator = existingUsers.iterator(); eIterator
.hasNext();) {
if (count == 0) {
accounts = (String) eIterator.next();
} else {
accounts = accounts + ", " + (String) eIterator.next();
}
count++;
}
addAlert(state, rb.getString("add.existingpart.1") + accounts
+ rb.getString("add.existingpart.2"));
}
return;
} // checkAddParticipant
private Vector removeDuplicateParticipants(List pList, SessionState state) {
// check the uniqness of list member
Set s = new HashSet();
Set uniqnameSet = new HashSet();
Vector rv = new Vector();
for (int i = 0; i < pList.size(); i++) {
Participant p = (Participant) pList.get(i);
if (!uniqnameSet.contains(p.getUniqname())) {
// no entry for the account yet
rv.add(p);
uniqnameSet.add(p.getUniqname());
} else {
// found duplicates
s.add(p.getUniqname());
}
}
if (!s.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator i = s.iterator(); i.hasNext();) {
if (count == 0) {
accounts = (String) i.next();
} else {
accounts = accounts + ", " + (String) i.next();
}
count++;
}
if (count == 1) {
addAlert(state, rb.getString("add.duplicatedpart.single")
+ accounts + ".");
} else {
addAlert(state, rb.getString("add.duplicatedpart") + accounts
+ ".");
}
}
return rv;
}
public void doAdd_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteTitle = getStateSite(state).getTitle();
String emailInIdAccountName = ServerConfigurationService.getString(
"emailInIdAccountName", "");
Hashtable selectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
boolean notify = false;
if (state.getAttribute("form_selectedNotify") != null) {
notify = ((Boolean) state.getAttribute("form_selectedNotify"))
.booleanValue();
}
boolean same_role = ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
Hashtable eIdRoles = new Hashtable();
List addParticipantList = (List) state
.getAttribute(STATE_ADD_PARTICIPANTS);
for (int i = 0; i < addParticipantList.size(); i++) {
Participant p = (Participant) addParticipantList.get(i);
String eId = p.getEid();
// role defaults to same role
String role = (String) state.getAttribute("form_selectedRole");
if (!same_role) {
// if all added participants have different role
role = (String) selectedRoles.get(eId);
}
boolean noEmailInIdAccount = eId.indexOf(EMAIL_CHAR) == -1;
if (noEmailInIdAccount) {
// if this is a noEmailInIdAccount
// update the hashtable
eIdRoles.put(eId, role);
} else {
// if this is an emailInIdAccount
try {
UserDirectoryService.getUserByEid(eId);
} catch (UserNotDefinedException e) {
// if there is no such user yet, add the user
try {
UserEdit uEdit = UserDirectoryService
.addUser(null, eId);
// set email address
uEdit.setEmail(eId);
// set the guest user type
uEdit.setType("guest");
// set password to a positive random number
Random generator = new Random(System
.currentTimeMillis());
Integer num = new Integer(generator
.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0)
num = new Integer(num.intValue() * -1);
String pw = num.toString();
uEdit.setPassword(pw);
// and save
UserDirectoryService.commitEdit(uEdit);
boolean notifyNewUserEmail = (ServerConfigurationService
.getString("notifyNewUserEmail", Boolean.TRUE
.toString()))
.equalsIgnoreCase(Boolean.TRUE.toString());
if (notifyNewUserEmail) {
notifyNewUserEmail(uEdit.getEid(),
uEdit.getEmail(), pw, siteTitle);
}
} catch (UserIdInvalidException ee) {
addAlert(state, emailInIdAccountName + " id " + eId
+ " " + rb.getString("java.isinval"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserAlreadyDefinedException ee) {
addAlert(state, "The " + emailInIdAccountName + " "
+ eId + " " + rb.getString("java.beenused"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserPermissionException ee) {
addAlert(state, rb.getString("java.haveadd") + " "
+ eId);
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
eIdRoles.put(eId, role);
}
}
}
// batch add and updates the successful added list
List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify,
false);
// update the not added user list
String notAddedNoEmailInIdAccounts = null;
String notAddedEmailInIdAccounts = null;
for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) {
String iEId = (String) iEIds.next();
if (!addedParticipantEIds.contains(iEId)) {
if (iEId.indexOf(EMAIL_CHAR) == -1) {
// no email in eid
notAddedNoEmailInIdAccounts = notAddedNoEmailInIdAccounts
.concat(iEId + "\n");
} else {
// email in eid
notAddedEmailInIdAccounts = notAddedEmailInIdAccounts
.concat(iEId + "\n");
}
}
}
if (addedParticipantEIds.size() != 0
&& (notAddedNoEmailInIdAccounts != null || notAddedEmailInIdAccounts != null)) {
// at lease one noEmailInIdAccount account or an emailInIdAccount
// account added, and there are also failures
addAlert(state, rb.getString("java.allusers"));
}
if (notAddedNoEmailInIdAccounts == null
&& notAddedEmailInIdAccounts == null) {
// all account has been added successfully
removeAddParticipantContext(state);
} else {
state.setAttribute("noEmailInIdAccountValue",
notAddedNoEmailInIdAccounts);
state.setAttribute("emailInIdAccountValue",
notAddedEmailInIdAccounts);
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "22");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
return;
} // doAdd_participant
/**
* remove related state variable for adding participants
*
* @param state
* SessionState object
*/
private void removeAddParticipantContext(SessionState state) {
// remove related state variables
state.removeAttribute("form_selectedRole");
state.removeAttribute("noEmailInIdAccountValue");
state.removeAttribute("emailInIdAccountValue");
state.removeAttribute("form_same_role");
state.removeAttribute("form_selectedNotify");
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeAddParticipantContext
/**
* Send an email to newly added user informing password
*
* @param newEmailInIdAccount
* @param emailId
* @param userName
* @param siteTitle
*/
private void notifyNewUserEmail(String userName, String newUserEmail,
String newUserPassword, String siteTitle) {
String from = getSetupRequestEmailAddress();
String productionSiteName = ServerConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = ServerConfigurationService.getPortalUrl();
String to = newUserEmail;
String headerTo = newUserEmail;
String replyTo = newUserEmail;
String message_subject = productionSiteName + " "
+ rb.getString("java.newusernoti");
String content = "";
if (from != null && newUserEmail != null) {
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.addedto") + " " + productionSiteName
+ " (" + productionSiteUrl + ") ");
buf.append(rb.getString("java.simpleby") + " ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName()
+ ". \n\n");
buf.append(rb.getString("java.passwordis1") + "\n"
+ newUserPassword + "\n\n");
buf.append(rb.getString("java.passwordis2") + "\n\n");
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
}
} // notifyNewUserEmail
private String getSetupRequestEmailAddress() {
String from = ServerConfigurationService.getString("setup.request",
null);
if (from == null) {
M_log.warn(this + " - no 'setup.request' in configuration");
from = "postmaster@".concat(ServerConfigurationService
.getServerName());
}
return from;
}
/**
* send email notification to added participant
*/
private void notifyAddedParticipant(boolean newEmailInIdAccount,
String emailId, String userName, String siteTitle) {
String from = getSetupRequestEmailAddress();
if (from != null) {
String productionSiteName = ServerConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = ServerConfigurationService
.getPortalUrl();
String emailInIdAccountUrl = ServerConfigurationService.getString(
"emailInIdAccount.url", null);
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
String message_subject = productionSiteName + " "
+ rb.getString("java.sitenoti");
String content = "";
StringBuffer buf = new StringBuffer();
buf.setLength(0);
// email body differs between newly added emailInIdAccount account
// and other users
buf.append(userName + ":\n\n");
buf.append(rb.getString("java.following") + " "
+ productionSiteName + " "
+ rb.getString("java.simplesite") + "\n");
buf.append(siteTitle + "\n");
buf.append(rb.getString("java.simpleby") + " ");
buf.append(UserDirectoryService.getCurrentUser().getDisplayName()
+ ". \n\n");
if (newEmailInIdAccount) {
buf.append(ServerConfigurationService.getString(
"emailInIdAccountInstru", "")
+ "\n");
if (emailInIdAccountUrl != null) {
buf.append(rb.getString("java.togeta1") + "\n"
+ emailInIdAccountUrl + "\n");
buf.append(rb.getString("java.togeta2") + "\n\n");
}
buf.append(rb.getString("java.once") + " " + productionSiteName
+ ": \n");
buf.append(rb.getString("java.loginhow1") + " "
+ productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2") + "\n");
buf.append(rb.getString("java.loginhow3") + "\n");
} else {
buf.append(rb.getString("java.tolog") + "\n");
buf.append(rb.getString("java.loginhow1") + " "
+ productionSiteName + ": " + productionSiteUrl + "\n");
buf.append(rb.getString("java.loginhow2") + "\n");
buf.append(rb.getString("java.loginhow3u") + "\n");
}
buf.append(rb.getString("java.tabscreen"));
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
} // if
} // notifyAddedParticipant
/*
* Given a list of user eids, add users to realm If the user account does
* not exist yet inside the user directory, assign role to it @return A list
* of eids for successfully added users
*/
private List addUsersRealm(SessionState state, Hashtable eIdRoles,
boolean notify, boolean emailInIdAccount) {
// return the list of user eids for successfully added user
List addedUserEIds = new Vector();
StringBuffer message = new StringBuffer();
if (eIdRoles != null && !eIdRoles.isEmpty()) {
// get the current site
Site sEdit = getStateSite(state);
if (sEdit != null) {
// get realm object
String realmId = sEdit.getReference();
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realmId);
for (Iterator eIds = eIdRoles.keySet().iterator(); eIds
.hasNext();) {
String eId = (String) eIds.next();
String role = (String) eIdRoles.get(eId);
try {
User user = UserDirectoryService.getUserByEid(eId);
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService
.allowUpdateSiteMembership(sEdit
.getId())) {
realmEdit.addMember(user.getId(), role, true,
false);
addedUserEIds.add(eId);
// send notification
if (notify) {
String emailId = user.getEmail();
String userName = user.getDisplayName();
// send notification email
notifyAddedParticipant(emailInIdAccount,
emailId, userName, sEdit.getTitle());
}
}
} catch (UserNotDefinedException e) {
message.append(eId + " "
+ rb.getString("java.account") + " \n");
} // try
} // for
try {
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException ee) {
message.append(rb.getString("java.realm") + realmId);
} catch (AuthzPermissionException ee) {
message.append(rb.getString("java.permeditsite")
+ realmId);
}
} catch (GroupNotDefinedException eee) {
message.append(rb.getString("java.realm") + realmId);
}
}
}
if (message.length() != 0) {
addAlert(state, message.toString());
} // if
return addedUserEIds;
} // addUsersRealm
/**
* addNewSite is called when the site has enough information to create a new
* site
*
*/
private void addNewSite(ParameterParser params, SessionState state) {
if (getStateSite(state) != null) {
// There is a Site in state already, so use it rather than creating
// a new Site
return;
}
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtil.trimToNull(siteInfo.getSiteId());
if (id == null) {
// get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
Site site = SiteService.addSite(id, siteInfo.site_type);
String title = StringUtil.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null) {
site.setTitle(title);
}
site.setType(siteInfo.site_type);
ResourcePropertiesEdit rp = site.getPropertiesEdit();
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(PROP_SITE_CONTACT_NAME,
siteInfo.site_contact_name);
rp.addProperty(PROP_SITE_CONTACT_EMAIL,
siteInfo.site_contact_email);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
// commit newly added site in order to enable related realm
commitSite(site);
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitewithid") + " " + id
+ " " + rb.getString("java.exists"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.thesiteid") + " " + id + " "
+ rb.getString("java.notvalid"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (PermissionException e) {
addAlert(state, rb.getString("java.permission") + " " + id
+ ".");
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
}
}
} // addNewSite
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState(SessionState state) {
try {
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
} catch (Exception e) {
M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage());
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns true if a SitePage matches a WorkSite Setup
* pattern
*
*/
private boolean pageMatchesPattern(SessionState state, SitePage page) {
List pageToolList = page.getTools();
// if no tools on the page, return false
if (pageToolList == null || pageToolList.size() == 0) {
return false;
}
// for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList
.get(0);
// don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
boolean match = false;
// check Worksite Setup Home pattern
if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.home"))) {
return true;
} // Home
else if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.help"))) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if tooId isn't sakai.contactSupport, return false
if (!(toolConfiguration.getTool().getId())
.equals("sakai.contactSupport")) {
return false;
}
return true;
} // Help
else if (page.getTitle() != null && page.getTitle().equals("Chat")) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if the tool doesn't match, return false
if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) {
return false;
}
// if the channel doesn't match value for main channel, return false
String channel = toolConfiguration.getPlacementConfig()
.getProperty("channel");
if (channel == null) {
return false;
}
if (!(channel.equals(NULL_STRING))) {
return false;
}
return true;
} // Chat
else {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if (pageToolList != null || pageToolList.size() != 0) {
// if tool attributes don't match, return false
match = false;
for (ListIterator i = toolList.listIterator(); i.hasNext();) {
MyTool tool = (MyTool) i.next();
if (toolConfiguration.getTitle() != null) {
if (toolConfiguration.getTool() != null
&& toolConfiguration.getTool().getId().indexOf(
tool.getId()) != -1) {
match = true;
}
}
}
if (!match) {
return false;
}
}
} // Others
return true;
} // pageMatchesPattern
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list
* of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState(SessionState state) {
String wSetupTool = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state);
List pageList = site.getPages();
// Put up tool lists filtered by category
String type = site.getType();
if (type == null) {
if (SiteService.isUserSite(site.getId())) {
type = "myworkspace";
} else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// for those sites without type, use the tool set for default
// site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
List toolRegList = new Vector();
if (type != null) {
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
if (toolRegList.size() == 0
&& state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
Set nCategories = new HashSet();
nCategories.add(type);
Set toolRegistrations = ToolManager.findTools(nCategories, null);
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
toolRegList.add(newTool);
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_SITE_TYPE, type);
if (type == null) {
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
} else {
state.setAttribute(STATE_SITE_TYPE, type);
}
boolean check_home = false;
boolean hasNews = false;
boolean hasWebContent = false;
int newsToolNum = 0;
int wcToolNum = 0;
Hashtable newsTitles = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcUrls = new Hashtable();
Vector idSelected = new Vector();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
// collect the pages consistent with Worksite Setup patterns
if (pageMatchesPattern(state, page)) {
if (page.getTitle().equals(rb.getString("java.home"))) {
wSetupTool = HOME_TOOL_ID;
check_home = true;
} else {
List pageToolList = page.getTools();
wSetupTool = ((ToolConfiguration) pageToolList.get(0))
.getTool().getId();
if (wSetupTool.indexOf("sakai.news") != -1) {
String newsToolId = page.getId() + wSetupTool;
idSelected.add(newsToolId);
newsTitles.put(newsToolId, page.getTitle());
String channelUrl = ((ToolConfiguration) pageToolList
.get(0)).getPlacementConfig().getProperty(
"channel-url");
newsUrls.put(newsToolId,
channelUrl != null ? channelUrl : "");
newsToolNum++;
// insert the News tool into the list
hasNews = false;
int j = 0;
MyTool newTool = new MyTool();
newTool.title = NEWS_DEFAULT_TITLE;
newTool.id = newsToolId;
newTool.selected = false;
for (; j < toolRegList.size() && !hasNews; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.news")) {
hasNews = true;
newTool.description = t.getDescription();
}
}
if (hasNews) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
} else if ((wSetupTool).indexOf("sakai.iframe") != -1) {
String wcToolId = page.getId() + wSetupTool;
idSelected.add(wcToolId);
wcTitles.put(wcToolId, page.getTitle());
String wcUrl = StringUtil
.trimToNull(((ToolConfiguration) pageToolList
.get(0)).getPlacementConfig()
.getProperty("source"));
if (wcUrl == null) {
// if there is no source URL, seed it with the
// Web Content default URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
}
wcUrls.put(wcToolId, wcUrl);
wcToolNum++;
MyTool newTool = new MyTool();
newTool.title = WEB_CONTENT_DEFAULT_TITLE;
newTool.id = wcToolId;
newTool.selected = false;
hasWebContent = false;
int j = 0;
for (; j < toolRegList.size() && !hasWebContent; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals("sakai.iframe")) {
hasWebContent = true;
newTool.description = t.getDescription();
}
}
if (hasWebContent) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
}
/*
* else if(wSetupTool.indexOf("sakai.syllabus") != -1) {
* //add only one instance of tool per site if
* (!(idSelected.contains(wSetupTool))) {
* idSelected.add(wSetupTool); } }
*/
else {
idSelected.add(wSetupTool);
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List
// of
// ToolRegistration
// toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,
idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean
.valueOf(check_home));
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} // siteToolsIntoState
/**
* reset the state variables used in edit tools mode
*
* @state The SessionState object
*/
private void removeEditToolState(SessionState state) {
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_NEWS_TITLES);
state.removeAttribute(STATE_NEWS_URLS);
state.removeAttribute(STATE_WEB_CONTENT_TITLES);
state.removeAttribute(STATE_WEB_CONTENT_URLS);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
}
private List orderToolIds(SessionState state, String type, List toolIdList) {
List rv = new Vector();
if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED))
.booleanValue()) {
rv.add(HOME_TOOL_ID);
}
// look for null site type
if (type != null && toolIdList != null) {
Set categories = new HashSet();
categories.add(type);
Set tools = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(tools.iterator(),
new ToolComparator());
for (; i.hasNext();) {
String tool_id = ((Tool) i.next()).getId();
for (ListIterator j = toolIdList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (toolId.indexOf("assignment") != -1
&& toolId.equals(tool_id)
|| toolId.indexOf("assignment") == -1
&& toolId.indexOf(tool_id) != -1) {
rv.add(toolId);
}
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state) {
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear()
+ ", " + UserDirectoryService.getCurrentUser().getDisplayName()
+ ". All Rights Reserved. ";
state.setAttribute(STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute(STATE_SITE_INSTANCE_ID, null);
state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
// legacy
state.setAttribute(FORM_HONORIFIC, "0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
// sundry form variables
state.setAttribute(FORM_PHONE, "");
state.setAttribute(FORM_EMAIL, "");
state.setAttribute(FORM_SUBJECT, "");
state.setAttribute(FORM_DESCRIPTION, "");
state.setAttribute(FORM_TITLE, "");
state.setAttribute(FORM_NAME, "");
state.setAttribute(FORM_SHORT_DESCRIPTION, "");
} // setupFormNamesAndConstants
/**
* setupSkins
*
*/
private void setupIcons(SessionState state) {
List icons = new Vector();
String[] iconNames = null;
String[] iconUrls = null;
String[] iconSkins = null;
// get icon information
if (ServerConfigurationService.getStrings("iconNames") != null) {
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null) {
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null) {
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null)
&& (iconNames.length == iconUrls.length)
&& (iconNames.length == iconSkins.length)) {
for (int i = 0; i < iconNames.length; i++) {
MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]),
StringUtil.trimToNull((String) iconUrls[i]), StringUtil
.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl) {
// set the icon
edit.setIconUrl(iconUrl);
if (iconUrl == null) {
// this is the default case - no icon, no (default) skin
edit.setSkin(null);
return;
}
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();) {
Object icon = (Object) i.next();
if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) {
edit.setSkin(((MyIcon) icon).getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("addNews")) {
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.news", STATE_NEWS_TITLES,
NEWS_DEFAULT_TITLE, STATE_NEWS_URLS, NEWS_DEFAULT_URL,
Integer.parseInt(params.getString("newsNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else if (option.equalsIgnoreCase("addWC")) {
updateSelectedToolList(state, params, false);
insertTool(state, "sakai.iframe", STATE_WEB_CONTENT_TITLES,
WEB_CONTENT_DEFAULT_TITLE, STATE_WEB_CONTENT_URLS,
WEB_CONTENT_DEFAULT_URL, Integer.parseInt(params
.getString("wcNum")));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else if (option.equalsIgnoreCase("import")) {
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null
&& importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
} else if (option.equalsIgnoreCase("continue")) {
// continue
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
// cancel
doCancel_create(data);
}
} // doAdd_features
/**
* update the selected tool list
*
* @param params
* The ParameterParser object
* @param verifyData
* Need to verify input data or not
*/
private void updateSelectedToolList(SessionState state,
ParameterParser params, boolean verifyData) {
List selectedTools = new ArrayList(Arrays.asList(params
.getStrings("selectedTools")));
Hashtable titles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
Hashtable urls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
Hashtable wcTitles = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES);
Hashtable wcUrls = (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_URLS);
boolean has_home = false;
String emailId = null;
for (int i = 0; i < selectedTools.size(); i++) {
String id = (String) selectedTools.get(i);
if (id.indexOf("sakai.news") != -1) {
String title = StringUtil.trimToNull(params
.getString("titlefor" + id));
if (title == null) {
// if there is no input, make the title for news tool
// default to NEWS_DEFAULT_TITLE
title = NEWS_DEFAULT_TITLE;
}
titles.put(id, title);
String url = StringUtil.trimToNull(params.getString("urlfor"
+ id));
if (url == null) {
// if there is no input, make the title for news tool
// default to NEWS_DEFAULT_URL
url = NEWS_DEFAULT_URL;
}
urls.put(id, url);
try {
new URL(url);
} catch (MalformedURLException e) {
addAlert(state, rb.getString("java.invurl") + " " + url
+ ". ");
}
} else if (id.indexOf("sakai.iframe") != -1) {
String wcTitle = StringUtil.trimToNull(params
.getString("titlefor" + id));
if (wcTitle == null) {
// if there is no input, make the title for Web Content tool
// default to WEB_CONTENT_DEFAULT_TITLE
wcTitle = WEB_CONTENT_DEFAULT_TITLE;
}
wcTitles.put(id, wcTitle);
String wcUrl = StringUtil.trimToNull(params.getString("urlfor"
+ id));
if (wcUrl == null) {
// if there is no input, make the title for Web Content tool
// default to WEB_CONTENT_DEFAULT_URL
wcUrl = WEB_CONTENT_DEFAULT_URL;
} else {
if ((wcUrl.length() > 0) && (!wcUrl.startsWith("/"))
&& (wcUrl.indexOf("://") == -1)) {
wcUrl = "http://" + wcUrl;
}
}
wcUrls.put(id, wcUrl);
} else if (id.equalsIgnoreCase(HOME_TOOL_ID)) {
has_home = true;
} else if (id.equalsIgnoreCase("sakai.mailbox")) {
// if Email archive tool is selected, check the email alias
emailId = StringUtil.trimToNull(params.getString("emailId"));
if (verifyData) {
if (emailId == null) {
addAlert(state, rb.getString("java.emailarchive") + " ");
} else {
if (!Validator.checkEmailLocal(emailId)) {
addAlert(state, rb.getString("java.theemail"));
} else {
// check to see whether the alias has been used by
// other sites
try {
String target = AliasService.getTarget(emailId);
if (target != null) {
if (state
.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
String siteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (!target.equals(channelReference)) {
// the email alias is not used by
// current site
addAlert(
state,
rb
.getString("java.emailinuse")
+ " ");
}
} else {
addAlert(state, rb
.getString("java.emailinuse")
+ " ");
}
}
} catch (IdUnusedException ee) {
}
}
}
}
}
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
state.setAttribute(STATE_NEWS_TITLES, titles);
state.setAttribute(STATE_NEWS_URLS, urls);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
} // updateSelectedToolList
/**
* find the tool in the tool list and insert another tool instance to the
* list
*
* @param state
* SessionState object
* @param toolId
* The id for the inserted tool
* @param stateTitlesVariable
* The titles
* @param defaultTitle
* The default title for the inserted tool
* @param stateUrlsVariable
* The urls
* @param defaultUrl
* The default url for the inserted tool
* @param insertTimes
* How many tools need to be inserted
*/
private void insertTool(SessionState state, String toolId,
String stateTitlesVariable, String defaultTitle,
String stateUrlsVariable, String defaultUrl, int insertTimes) {
// the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
int toolListedTimes = 0;
int index = 0;
int insertIndex = 0;
while (index < toolList.size()) {
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1) {
toolListedTimes++;
}
if (toolListedTimes > 0 && insertIndex == 0) {
// update the insert index
insertIndex = index;
}
index++;
}
List toolSelected = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// the titles
Hashtable titles = (Hashtable) state.getAttribute(stateTitlesVariable);
if (titles == null) {
titles = new Hashtable();
}
// the urls
Hashtable urls = (Hashtable) state.getAttribute(stateUrlsVariable);
if (urls == null) {
urls = new Hashtable();
}
// insert multiple tools
for (int i = 0; i < insertTimes; i++) {
toolListedTimes = toolListedTimes + i;
toolSelected.add(toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific
// tool entries have been selected
MyTool newTool = new MyTool();
newTool.title = defaultTitle;
newTool.id = toolId + toolListedTimes;
toolList.add(insertIndex, newTool);
titles.put(newTool.id, defaultTitle);
urls.put(newTool.id, defaultUrl);
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
state.setAttribute(stateTitlesVariable, titles);
state.setAttribute(stateUrlsVariable, urls);
} // insertTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state) {
List selectedUserIds = (List) state
.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = (List) state
.getAttribute(STATE_PARTICIPANT_LIST);
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if (!selectedUserIds.isEmpty() && participantList != null) {
for (int i = 0; i < participantList.size(); i++) {
String id = "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class)) {
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o)
.getRole());
} else if (o.getClass().equals(Student.class)) {
// get participant from roster role
id = ((Student) o).getUniqname();
selectedParticipantRoles.put(id, ((Student) o).getRole());
}
if (selectedUserIds.contains(id)) {
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
selectedParticipantRoles);
state
.setAttribute(STATE_SELECTED_PARTICIPANTS,
selectedParticipantList);
} // setSelectedParticipantRol3es
/**
* the SiteComparator class
*/
private class SiteComparator implements Comparator {
Collator collator = Collator.getInstance();
/**
* the criteria
*/
String m_criterion = null;
String m_asc = null;
/**
* constructor
*
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false"
* otherwise.
*/
public SiteComparator(String criterion, String asc) {
m_criterion = criterion;
m_asc = asc;
} // constructor
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2) {
int result = -1;
if (m_criterion == null)
m_criterion = SORTED_BY_TITLE;
/** *********** for sorting site list ****************** */
if (m_criterion.equals(SORTED_BY_TITLE)) {
// sorted by the worksite title
String s1 = ((Site) o1).getTitle();
String s2 = ((Site) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_DESCRIPTION)) {
// sorted by the site short description
String s1 = ((Site) o1).getShortDescription();
String s2 = ((Site) o2).getShortDescription();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_TYPE)) {
// sorted by the site type
String s1 = ((Site) o1).getType();
String s2 = ((Site) o2).getType();
result = compareString(s1, s2);
} else if (m_criterion.equals(SortType.CREATED_BY_ASC.toString())) {
// sorted by the site creator
String s1 = ((Site) o1).getProperties().getProperty(
"CHEF:creator");
String s2 = ((Site) o2).getProperties().getProperty(
"CHEF:creator");
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_STATUS)) {
// sort by the status, published or unpublished
int i1 = ((Site) o1).isPublished() ? 1 : 0;
int i2 = ((Site) o2).isPublished() ? 1 : 0;
if (i1 > i2) {
result = 1;
} else {
result = -1;
}
} else if (m_criterion.equals(SORTED_BY_JOINABLE)) {
// sort by whether the site is joinable or not
boolean b1 = ((Site) o1).isJoinable();
boolean b2 = ((Site) o2).isJoinable();
if (b1 == b2) {
result = 0;
} else if (b1 == true) {
result = 1;
} else {
result = -1;
}
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_NAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getName();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getName();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_UNIQNAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getUniqname();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getUniqname();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ROLE)) {
String s1 = "";
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRole();
}
String s2 = "";
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRole();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_COURSE)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getSection();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getSection();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ID)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRegId();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRegId();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_CREDITS)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getCredits();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getCredits();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_CREATION_DATE)) {
// sort by the site's creation date
Time t1 = null;
Time t2 = null;
// get the times
try {
t1 = ((Site) o1).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
try {
t2 = ((Site) o2).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
if (t1 == null) {
result = -1;
} else if (t2 == null) {
result = 1;
} else if (t1.before(t2)) {
result = -1;
} else {
result = 1;
}
} else if (m_criterion.equals(rb.getString("group.title"))) {
// sorted by the group title
String s1 = ((Group) o1).getTitle();
String s2 = ((Group) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(rb.getString("group.number"))) {
// sorted by the group title
int n1 = ((Group) o1).getMembers().size();
int n2 = ((Group) o2).getMembers().size();
result = (n1 > n2) ? 1 : -1;
} else if (m_criterion.equals(SORTED_BY_MEMBER_NAME)) {
// sorted by the member name
String s1 = null;
String s2 = null;
try {
s1 = UserDirectoryService
.getUser(((Member) o1).getUserId()).getSortName();
} catch (Exception ignore) {
}
try {
s2 = UserDirectoryService
.getUser(((Member) o2).getUserId()).getSortName();
} catch (Exception ignore) {
}
result = compareString(s1, s2);
}
if (m_asc == null)
m_asc = Boolean.TRUE.toString();
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString())) {
result = -result;
}
return result;
} // compare
private int compareString(String s1, String s2) {
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1, s2);
}
return result;
}
} // SiteComparator
private class ToolComparator implements Comparator {
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1
* otherwise
*/
public int compare(Object o1, Object o2) {
try {
return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle());
} catch (Exception e) {
}
return -1;
} // compare
} // ToolComparator
public class MyIcon {
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public MyIcon(String name, String url, String skin) {
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() {
return m_name;
}
public String getUrl() {
return m_url;
}
public String getSkin() {
return m_skin;
}
}
// a utility class for form select options
public class IdAndText {
public int id;
public String text;
public int getId() {
return id;
}
public String getText() {
return text;
}
} // IdAndText
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id =
// chosen-feature.id is a direct mapping of data
public class MyTool {
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public boolean getSelected() {
return selected;
}
}
/*
* WorksiteSetupPage is a utility class for working with site pages
* configured by Worksite Setup
*
*/
public class WorksiteSetupPage {
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() {
return pageId;
}
public String getPageTitle() {
return pageTitle;
}
public String getToolId() {
return toolId;
}
} // WorksiteSetupPage
/**
* Participant in site access roles
*
*/
public class Participant {
public String name = NULL_STRING;
// Note: uniqname is really a user ID
public String uniqname = NULL_STRING;
public String role = NULL_STRING;
/** role from provider */
public String providerRole = NULL_STRING;
/** The member credits */
protected String credits = NULL_STRING;
/** The section */
public String section = NULL_STRING;
/** The regestration id */
public String regId = NULL_STRING;
/** removeable if not from provider */
public boolean removeable = true;
public String getName() {
return name;
}
public String getUniqname() {
return uniqname;
}
public String getRole() {
return role;
} // cast to Role
public String getProviderRole() {
return providerRole;
}
public boolean isRemoveable() {
return removeable;
}
// extra info from provider
public String getCredits() {
return credits;
} // getCredits
public String getSection() {
return section;
} // getSection
public String getRegId() {
return regId;
} // getRegId
/**
* Access the user eid, if we can find it - fall back to the id if not.
*
* @return The user eid.
*/
public String getEid() {
try {
return UserDirectoryService.getUserEid(uniqname);
} catch (UserNotDefinedException e) {
return uniqname;
}
}
/**
* Access the user display id, if we can find it - fall back to the id
* if not.
*
* @return The user display id.
*/
public String getDisplayId() {
try {
User user = UserDirectoryService.getUser(uniqname);
return user.getDisplayId();
} catch (UserNotDefinedException e) {
return uniqname;
}
}
} // Participant
/**
* Student in roster
*
*/
public class Student {
public String name = NULL_STRING;
public String uniqname = NULL_STRING;
public String id = NULL_STRING;
public String level = NULL_STRING;
public String credits = NULL_STRING;
public String role = NULL_STRING;
public String course = NULL_STRING;
public String section = NULL_STRING;
public String getName() {
return name;
}
public String getUniqname() {
return uniqname;
}
public String getId() {
return id;
}
public String getLevel() {
return level;
}
public String getCredits() {
return credits;
}
public String getRole() {
return role;
}
public String getCourse() {
return course;
}
public String getSection() {
return section;
}
} // Student
public class SiteInfo {
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id
// connects site with U-M
// course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public String short_description = NULL_STRING; // the short (20 char)
// description of the
// site
public String description = NULL_STRING; // the longer description of
// the site
public String additional = NULL_STRING; // additional information on
// crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index;
// default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String getSiteId() {
return site_id;
}
public String getSiteType() {
return site_type;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public String getInfoUrll() {
return infoUrl;
}
public boolean getJoinable() {
return joinable;
}
public String getJoinerRole() {
return joinerRole;
}
public String getAdditional() {
return additional;
}
public boolean getPublished() {
return published;
}
public boolean getInclude() {
return include;
}
public String getSiteContactName() {
return site_contact_name;
}
public String getSiteContactEmail() {
return site_contact_email;
}
} // SiteInfo
// dissertation tool related
/**
* doFinish_grad_tools is called when creation of a Grad Tools site is
* confirmed
*/
public void doFinish_grad_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
// add the pre-configured Grad Tools tools to a new site
addGradToolsFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_grad_tools
/**
* addGradToolsFeatures adds features to a new Grad Tools student site
*
*/
private void addGradToolsFeatures(SessionState state) {
Site edit = null;
Site template = null;
// get a unique id
String id = IdManager.createUuid();
// get the Grad Tools student site template
try {
template = SiteService.getSite(SITE_GTS_TEMPLATE);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures template " + e);
}
if (template != null) {
// create a new site based on the template
try {
edit = SiteService.addSite(id, template);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures add/edit site " + e);
}
// set the tab, etc.
if (edit != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
edit.setType(SITE_TYPE_GRADTOOLS_STUDENT);
// ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
try {
SiteService.save(edit);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeartures commitEdit " + e);
}
// now that the site and realm exist, we can set the email alias
// set the GradToolsStudent site alias as:
// gradtools-uniqname@servername
String alias = "gradtools-"
+ SessionManager.getCurrentSessionUserId();
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
M_log.warn(SessionManager.getCurrentSessionUserId()
+ " does not have permission to add alias. ");
}
}
}
} // addGradToolsFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("finish")) {
doFinish(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("duplicate")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel(data);
} else if (option.equals("finish")) {
doContinue(data);
}
} // doDuplicate_site_option
/**
* Special check against the Dissertation service, which might not be
* here...
*
* @return
*/
protected boolean isGradToolsCandidate(String userId) {
// DissertationService.isCandidate(userId) - but the hard way
Object service = ComponentManager
.get("org.sakaiproject.api.app.dissertation.DissertationService");
if (service == null)
return false;
// the method signature
Class[] signature = new Class[1];
signature[0] = String.class;
// the method name
String methodName = "isCandidate";
// find a method of this class with this name and signature
try {
Method method = service.getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[1];
args[0] = userId;
// make the call
Boolean rv = (Boolean) method.invoke(service, args);
return rv.booleanValue();
} catch (Throwable t) {
}
return false;
}
/**
* User has a Grad Tools student site
*
* @return
*/
protected boolean hasGradToolsStudentSite(String userId) {
boolean has = false;
int n = 0;
try {
n = SiteService.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
SITE_TYPE_GRADTOOLS_STUDENT, null, null);
if (n > 0)
has = true;
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("hasGradToolsStudentSite " + e);
}
return has;
}// hasGradToolsStudentSite
/**
* Get the mail archive channel reference for the main container placement
* for this site.
*
* @param siteId
* The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId) {
MailArchiveService m = (org.sakaiproject.mailarchive.api.MailArchiveService) ComponentManager
.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null) {
return m.channelReference(siteId, SiteService.MAIN_CONTAINER);
} else {
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity
* producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected void transferCopyEntities(String toolId, String fromContext,
String toContext) {
// TODO: used to offer to resources first - why? still needed? -ggolden
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
et.transferCopyEntities(fromContext, toContext,
new Vector());
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
}
/**
* @return Get a list of all tools that support the import (transfer copy)
* option
*/
protected Set importTools() {
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null) {
for (int t = 0; t < tools.length; t++) {
rv.add(tools[t]);
}
}
}
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for
* import
*/
protected List getToolsAvailableForImport(SessionState state) {
// The Web Content and News tools do not follow the standard rules for
// import
// Even if the current site does not contain the tool, News and WC will
// be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES))
.keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext()) {
Site site = (Site) sitesIter.next();
if (site.getToolForCommonId("sakai.iframe") != null)
displayWebContent = true;
if (site.getToolForCommonId("sakai.news") != null)
displayNews = true;
}
List toolsOnImportList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (displayWebContent && !toolsOnImportList.contains("sakai.iframe"))
toolsOnImportList.add("sakai.iframe");
if (displayNews && !toolsOnImportList.contains("sakai.news"))
toolsOnImportList.add("sakai.news");
return toolsOnImportList;
} // getToolsAvailableForImport
private void setTermListForContext(Context context, SessionState state,
boolean upcomingOnly) {
List terms;
if (upcomingOnly) {
terms = cms.getCurrentAcademicSessions();
} else { // get all
terms = cms.getAcademicSessions();
}
if (terms != null && terms.size() > 0) {
context.put("termList", terms);
}
} // setTermListForContext
private void setSelectedTermForContext(Context context, SessionState state,
String stateAttribute) {
if (state.getAttribute(stateAttribute) != null) {
context.put("selectedTerm", state.getAttribute(stateAttribute));
}
} // setSelectedTermForContext
/**
* rewrote for 2.4
*
* @param userId
* @param academicSessionEid
* @param courseOfferingHash
* @param sectionHash
*/
private void prepareCourseAndSectionMap(String userId,
String academicSessionEid, HashMap courseOfferingHash,
HashMap sectionHash) {
// looking for list of courseOffering and sections that should be
// included in
// the selection list. The course offering must be offered
// 1. in the specific academic Session
// 2. that the specified user has right to attach its section to a
// course site
// map = (section.eid, sakai rolename)
if (groupProvider == null)
{
M_log.warn("Group provider not found");
return;
}
Map map = groupProvider.getGroupRolesForUser(userId);
if (map == null)
return;
Set keys = map.keySet();
Set roleSet = getRolesAllowedToAttachSection();
for (Iterator i = keys.iterator(); i.hasNext();) {
String sectionEid = (String) i.next();
String role = (String) map.get(sectionEid);
if (includeRole(role, roleSet)) {
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
// now consider those user with affiliated sections
List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid);
if (affiliatedSectionEids != null)
{
for (int k = 0; k < affiliatedSectionEids.size(); k++) {
String sectionEid = (String) affiliatedSectionEids.get(k);
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
} // prepareCourseAndSectionMap
private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) {
try {
section = cms.getSection(sectionEid);
} catch (IdNotFoundException e) {
M_log.warn(e.getMessage());
}
if (section != null) {
String courseOfferingEid = section.getCourseOfferingEid();
CourseOffering courseOffering = cms
.getCourseOffering(courseOfferingEid);
String sessionEid = courseOffering.getAcademicSession()
.getEid();
if (academicSessionEid.equals(sessionEid)) {
// a long way to the conclusion that yes, this course
// offering
// should be included in the selected list. Sigh...
// -daisyf
ArrayList sectionList = (ArrayList) sectionHash
.get(courseOffering.getEid());
if (sectionList == null) {
sectionList = new ArrayList();
}
sectionList.add(new SectionObject(section));
sectionHash.put(courseOffering.getEid(), sectionList);
courseOfferingHash.put(courseOffering.getEid(),
courseOffering);
}
}
}
/**
* for 2.4
*
* @param role
* @return
*/
private boolean includeRole(String role, Set roleSet) {
boolean includeRole = false;
for (Iterator i = roleSet.iterator(); i.hasNext();) {
String r = (String) i.next();
if (r.equals(role)) {
includeRole = true;
break;
}
}
return includeRole;
} // includeRole
protected Set getRolesAllowedToAttachSection() {
// Use !site.template.[site_type]
String azgId = "!site.template.course";
AuthzGroup azgTemplate;
try {
azgTemplate = AuthzGroupService.getAuthzGroup(azgId);
} catch (GroupNotDefinedException e) {
M_log.warn("Could not find authz group " + azgId);
return new HashSet();
}
Set roles = azgTemplate.getRolesIsAllowed("site.upd");
roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd"));
return roles;
} // getRolesAllowedToAttachSection
/**
* Here, we will preapre two HashMap: 1. courseOfferingHash stores
* courseOfferingId and CourseOffering 2. sectionHash stores
* courseOfferingId and a list of its Section We sorted the CourseOffering
* by its eid & title and went through them one at a time to construct the
* CourseObject that is used for the displayed in velocity. Each
* CourseObject will contains a list of CourseOfferingObject(again used for
* vm display). Usually, a CourseObject would only contain one
* CourseOfferingObject. A CourseObject containing multiple
* CourseOfferingObject implies that this is a cross-listing situation.
*
* @param userId
* @param academicSessionEid
* @return
*/
private List prepareCourseAndSectionListing(String userId,
String academicSessionEid, SessionState state) {
// courseOfferingHash = (courseOfferingEid, vourseOffering)
// sectionHash = (courseOfferingEid, list of sections)
HashMap courseOfferingHash = new HashMap();
HashMap sectionHash = new HashMap();
prepareCourseAndSectionMap(userId, academicSessionEid,
courseOfferingHash, sectionHash);
// courseOfferingHash & sectionHash should now be filled with stuffs
// put section list in state for later use
state.setAttribute(STATE_PROVIDER_SECTION_LIST,
getSectionList(sectionHash));
ArrayList offeringList = new ArrayList();
Set keys = courseOfferingHash.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
CourseOffering o = (CourseOffering) courseOfferingHash
.get((String) i.next());
offeringList.add(o);
}
Collection offeringListSorted = sortOffering(offeringList);
ArrayList resultedList = new ArrayList();
// use this to keep track of courseOffering that we have dealt with
// already
// this is important 'cos cross-listed offering is dealt with together
// with its
// equivalents
ArrayList dealtWith = new ArrayList();
for (Iterator j = offeringListSorted.iterator(); j.hasNext();) {
CourseOffering o = (CourseOffering) j.next();
if (!dealtWith.contains(o.getEid())) {
// 1. construct list of CourseOfferingObject for CourseObject
ArrayList l = new ArrayList();
CourseOfferingObject coo = new CourseOfferingObject(o,
(ArrayList) sectionHash.get(o.getEid()));
l.add(coo);
// 2. check if course offering is cross-listed
Set set = cms.getEquivalentCourseOfferings(o.getEid());
if (set != null)
{
for (Iterator k = set.iterator(); k.hasNext();) {
CourseOffering eo = (CourseOffering) k.next();
if (courseOfferingHash.containsKey(eo.getEid())) {
// => cross-listed, then list them together
CourseOfferingObject coo_equivalent = new CourseOfferingObject(
eo, (ArrayList) sectionHash.get(eo.getEid()));
l.add(coo_equivalent);
dealtWith.add(eo.getEid());
}
}
}
CourseObject co = new CourseObject(o, l);
dealtWith.add(o.getEid());
resultedList.add(co);
}
}
return resultedList;
} // prepareCourseAndSectionListing
/**
* Sort CourseOffering by order of eid, title uisng velocity SortTool
*
* @param offeringList
* @return
*/
private Collection sortOffering(ArrayList offeringList) {
return sortCmObject(offeringList);
/*
* List propsList = new ArrayList(); propsList.add("eid");
* propsList.add("title"); SortTool sort = new SortTool(); return
* sort.sort(offeringList, propsList);
*/
} // sortOffering
/**
* sort any Cm object such as CourseOffering, CourseOfferingObject,
* SectionObject provided object has getter & setter for eid & title
*
* @param list
* @return
*/
private Collection sortCmObject(List list) {
if (list != null) {
List propsList = new ArrayList();
propsList.add("eid");
propsList.add("title");
SortTool sort = new SortTool();
return sort.sort(list, propsList);
} else {
return list;
}
} // sortCmObject
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class SectionObject {
public Section section;
public String eid;
public String title;
public String category;
public String categoryDescription;
public boolean isLecture;
public boolean attached;
public String authorizer;
public SectionObject(Section section) {
this.section = section;
this.eid = section.getEid();
this.title = section.getTitle();
this.category = section.getCategory();
this.categoryDescription = cms
.getSectionCategoryDescription(section.getCategory());
if ("01.lct".equals(section.getCategory())) {
this.isLecture = true;
} else {
this.isLecture = false;
}
Set set = authzGroupService.getAuthzGroupIds(section.getEid());
if (set != null && !set.isEmpty()) {
this.attached = true;
} else {
this.attached = false;
}
}
public Section getSection() {
return section;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public String getCategoryDescription() {
return categoryDescription;
}
public boolean getIsLecture() {
return isLecture;
}
public boolean getAttached() {
return attached;
}
public String getAuthorizer() {
return authorizer;
}
public void setAuthorizer(String authorizer) {
this.authorizer = authorizer;
}
} // SectionObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseObject {
public String eid;
public String title;
public List courseOfferingObjects;
public CourseObject(CourseOffering offering, List courseOfferingObjects) {
this.eid = offering.getEid();
this.title = offering.getTitle();
this.courseOfferingObjects = courseOfferingObjects;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getCourseOfferingObjects() {
return courseOfferingObjects;
}
} // CourseObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseOfferingObject {
public String eid;
public String title;
public List sections;
public CourseOfferingObject(CourseOffering offering,
List unsortedSections) {
List propsList = new ArrayList();
propsList.add("category");
propsList.add("eid");
SortTool sort = new SortTool();
this.sections = new ArrayList();
if (unsortedSections != null) {
this.sections = (List) sort.sort(unsortedSections, propsList);
}
this.eid = offering.getEid();
this.title = offering.getTitle();
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getSections() {
return sections;
}
} // CourseOfferingObject constructor
/**
* get campus user directory for dispaly in chef_newSiteCourse.vm
*
* @return
*/
private String getCampusDirectory() {
return ServerConfigurationService.getString(
"site-manage.campusUserDirectory", null);
} // getCampusDirectory
private void removeAnyFlagedSection(SessionState state,
ParameterParser params) {
List all = new ArrayList();
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerCourseList != null) {
all.addAll(providerCourseList);
}
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
if (manualCourseList != null) {
all.addAll(manualCourseList);
}
for (int i = 0; i < all.size(); i++) {
String eid = (String) all.get(i);
String field = "removeSection" + eid;
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
// eid is in either providerCourseList or manualCourseList
// either way, just remove it
if (providerCourseList != null)
providerCourseList.remove(eid);
if (manualCourseList != null)
manualCourseList.remove(eid);
}
}
List<SectionObject> requestedCMSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedCMSections != null) {
for (int i = 0; i < requestedCMSections.size(); i++) {
SectionObject so = (SectionObject) requestedCMSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
requestedCMSections.remove(so);
}
}
if (requestedCMSections.size() == 0)
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
}
List<SectionObject> authorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSections != null) {
for (int i = 0; i < authorizerSections.size(); i++) {
SectionObject so = (SectionObject) authorizerSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
authorizerSections.remove(so);
}
}
if (authorizerSections.size() == 0)
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
}
// if list is empty, set to null. This is important 'cos null is
// the indication that the list is empty in the code. See case 2 on line
// 1081
if (manualCourseList != null && manualCourseList.size() == 0)
manualCourseList = null;
if (providerCourseList != null && providerCourseList.size() == 0)
providerCourseList = null;
}
private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state,
ParameterParser params, List providerChosenList) {
if (state.getAttribute(STATE_MESSAGE) == null) {
siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// site title is the title of the 1st section selected -
// daisyf's note
if (providerChosenList != null && providerChosenList.size() >= 1) {
String title = prepareTitle((List) state
.getAttribute(STATE_PROVIDER_SECTION_LIST),
providerChosenList);
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null
&& ("true").equals(params.getString("manualAdds"))) {
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
} else if (params.getString("findCourse") != null
&& ("true").equals(params.getString("findCourse"))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
prepFindPage(state);
} else {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null) {
// if revising a site, go to the confirmation
// page of adding classes
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else {
// if creating a site, go the the site
// information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
}
}
/**
* By default, courseManagement is implemented
*
* @return
*/
private boolean courseManagementIsImplemented() {
boolean returnValue = true;
String isImplemented = ServerConfigurationService.getString(
"site-manage.courseManagementSystemImplemented", "true");
if (("false").equals(isImplemented))
returnValue = false;
return returnValue;
}
private List getCMSubjects() {
String subjectCategory = getCMSubjectCategory();
if (cms == null || subjectCategory == null) {
return new ArrayList(0);
}
Collection c = sortCmObject(cms.findCourseSets(subjectCategory));
return (List) c;
}
private List getCMSections(String offeringEid) {
if (offeringEid == null || offeringEid.trim().length() == 0)
return null;
if (cms != null) {
Set sections = cms.getSections(offeringEid);
Collection c = sortCmObject(new ArrayList(sections));
return (List) c;
}
return new ArrayList(0);
}
private List getCMCourseOfferings(String subjectEid, String termID) {
if (subjectEid == null || subjectEid.trim().length() == 0
|| termID == null || termID.trim().length() == 0)
return null;
if (cms != null) {
Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// ,
// termID);
ArrayList returnList = new ArrayList();
Iterator coIt = offerings.iterator();
while (coIt.hasNext()) {
CourseOffering co = (CourseOffering) coIt.next();
AcademicSession as = co.getAcademicSession();
if (as != null && as.getEid().equals(termID))
returnList.add(co);
}
Collection c = sortCmObject(returnList);
return (List) c;
}
return new ArrayList(0);
}
private String getCMSubjectCategory() {
if (cmSubjectCategory == null) {
cmSubjectCategory = ServerConfigurationService
.getString("site-manage.cms.subject.category");
if (cmSubjectCategory == null) {
if (warnedNoSubjectCategory)
M_log
.debug(rb
.getString("nscourse.cm.configure.log.nosubjectcat"));
else {
M_log
.info(rb
.getString("nscourse.cm.configure.log.nosubjectcat"));
warnedNoSubjectCategory = true;
}
}
}
return cmSubjectCategory;
}
private List<String> getCMLevelLabels() {
List<String> rv = new Vector<String>();
List<SectionField> fields = sectionFieldProvider.getRequiredFields();
for (int k = 0; k < fields.size(); k++)
{
SectionField sectionField = (SectionField) fields.get(k);
rv.add(sectionField.getLabelKey());
}
return rv;
}
private void prepFindPage(SessionState state) {
final List cmLevels = getCMLevelLabels(), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
int lvlSz = 0;
if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) {
// TODO: no cm levels configured, redirect to manual add
return;
}
if (selections != null && selections.size() == lvlSz) {
Section sect = cms.getSection((String) selections.get(selections
.size() - 1));
SectionObject so = new SectionObject(sect);
state.setAttribute(STATE_CM_SELECTED_SECTION, so);
} else
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.setAttribute(STATE_CM_LEVELS, cmLevels);
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
// check the configuration setting for choosing next screen
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue())
{
// go to the course/section selection page
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
// skip the course/section selection page, go directly into the manually create course page
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
private void addRequestedSection(SessionState state) {
SectionObject so = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
String uniqueName = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
so.setAuthorizer(uniqueName);
if (so == null)
return;
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedSections == null) {
requestedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!requestedSections.contains(so))
requestedSections.add(so);
// if the title has not yet been set and there is just
// one section, set the title to that section's EID
if (requestedSections.size() == 1) {
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo == null) {
siteInfo = new SiteInfo();
}
if (siteInfo.title == null || siteInfo.title.trim().length() == 0) {
siteInfo.title = so.getEid();
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
public void doFind_course(RunData data) {
final SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
final ParameterParser params = data.getParameters();
final String option = params.get("option");
if (option != null)
{
if ("continue".equals(option))
{
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue())
{
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null)
{
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("noEmailInIdAccountName")
+ ". ");
}
else
{
try
{
UserDirectoryService.getUserByEid(uniqname);
addRequestedSection(state);
}
catch (UserNotDefinedException e)
{
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("noEmailInIdAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
else
{
addRequestedSection(state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
doContinue(data);
return;
} else if ("back".equals(option)) {
doBack(data);
return;
} else if ("cancel".equals(option)) {
doCancel_create(data);
return;
} else if (option.equals("add")) {
addRequestedSection(state);
return;
} else if (option.equals("manual")) {
// TODO: send to case 37
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
return;
} else if (option.equals("remove"))
removeAnyFlagedSection(state, params);
}
final List selections = new ArrayList(3);
int cmLevel = 3;
String deptChanged = params.get("deptChanged");
if ("true".equals(deptChanged)) {
// when dept changes, remove selection on courseOffering and
// courseSection
cmLevel = 1;
}
for (int i = 0; i < cmLevel; i++) {
String val = params.get("idField_" + i);
if (val == null || val.trim().length() < 1) {
break;
}
selections.add(val);
}
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
prepFindPage(state);
}
/**
* return the title of the 1st section in the chosen list that has an
* enrollment set. No discrimination on section category
*
* @param sectionList
* @param chosenList
* @return
*/
private String prepareTitle(List sectionList, List chosenList) {
String title = null;
HashMap map = new HashMap();
for (Iterator i = sectionList.iterator(); i.hasNext();) {
SectionObject o = (SectionObject) i.next();
map.put(o.getEid(), o.getSection());
}
for (int j = 0; j < chosenList.size(); j++) {
String eid = (String) chosenList.get(j);
Section s = (Section) map.get(eid);
// we will always has a title regardless but we prefer it to be the
// 1st section on the chosen list that has an enrollment set
if (j == 0) {
title = s.getTitle();
}
if (s.getEnrollmentSet() != null) {
title = s.getTitle();
break;
}
}
return title;
} // prepareTitle
/**
* return an ArrayList of SectionObject
*
* @param sectionHash
* contains an ArrayList collection of SectionObject
* @return
*/
private ArrayList getSectionList(HashMap sectionHash) {
ArrayList list = new ArrayList();
// values is an ArrayList of section
Collection c = sectionHash.values();
for (Iterator i = c.iterator(); i.hasNext();) {
ArrayList l = (ArrayList) i.next();
list.addAll(l);
}
return list;
}
private String getAuthorizers(SessionState state) {
String authorizers = "";
ArrayList list = (ArrayList) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
authorizers = (String) list.get(i);
} else {
authorizers = authorizers + ", " + list.get(i);
}
}
}
return authorizers;
}
private List prepareSectionObject(List sectionList, String userId) {
ArrayList list = new ArrayList();
if (sectionList != null) {
for (int i = 0; i < sectionList.size(); i++) {
String sectionEid = (String) sectionList.get(i);
Section s = cms.getSection(sectionEid);
SectionObject so = new SectionObject(s);
so.setAuthorizer(userId);
list.add(so);
}
}
return list;
}
}
| true | true | private String buildContextForTemplate(int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
// the Grad Tools site option is only presented to
// GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a grad student?
if (!isGradToolsCandidate(userId)) {
// not a gradstudent
remove = true;
}
} catch (Exception e) {
remove = true;
}
} else {
// not support for dissertation sites
remove = true;
}
// do not show this site type in views
// sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
// the Grad Tools site option is only presented to UM grad
// students
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a UM grad student?
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
// if I am a UM grad student, do I already have a Grad Tools
// site?
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
if (Log.isWarnEnabled()) {
M_log.warn("buildContextForTemplate chef_site-type.vm "
+ e);
}
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) {
context.put("typeSelected", siteInfo.site_type);
} else if (types.size() > 0) {
context.put("typeSelected", types.get(0));
}
setTermListForContext(context, state, true); // true => only
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
/*
* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
context.put("back", "53");
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
context.put("back", "36");
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
} else {
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "0");
context.put("template-index", "37");
}
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put("back", "1");
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
/*
* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// ToolRegistrations
// for
// template
// list
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
// The "Home" tool checkbox needs special treatment to be selected
// by
// default.
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
/*
* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
// Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
// get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
/*
* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties
// and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService
.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService
.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService
.getString("emailInIdAccountLabel"));
if (state.getAttribute("noEmailInIdAccountValue") != null) {
context.put("noEmailInIdAccountValue", (String) state
.getAttribute("noEmailInIdAccountValue"));
}
if (state.getAttribute("emailInIdAccountValue") != null) {
context.put("emailInIdAccountValue", (String) state
.getAttribute("emailInIdAccountValue"));
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 6:
/*
* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try {
List removeableList = (List) state
.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++) {
User user = UserDirectoryService
.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null) {
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
} catch (UserNotDefinedException ee) {
}
} catch (GroupNotDefinedException e) {
}
context.put("backIndex", "18");
return (String) getContext(data).get("template") + TEMPLATE[6];
case 7:
/*
* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[7];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 9:
/*
* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo) state
.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[9];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 11:
/*
* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[11];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite) {
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site access for GRADTOOLS
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course")) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site duplicate and import
// for GRADTOOLS type of sites
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership) {
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
// show the Add Participant menu
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,
sortedAsc));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants
.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties()
.getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null) {
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1) {
manualCourseList = new ArrayList(
Arrays.asList(manualCourseListString
.split("\\+")));
} else {
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try {
context.put("realm", AuthzGroupService
.getAuthzGroup(realmId));
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + realmId);
}
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null) {
context.put("selectedIcon", state
.getAttribute(FORM_SITEINFO_SKIN));
} else if (site.getIconUrl() != null) {
context.put("selectedIcon", site.getIconUrl());
}
setTermListForContext(context, state, true); // true->only future terms
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
// Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with
// sakai.properties file.
if ((ServerConfigurationService
.getString("disable.course.site.skin.selection"))
.equals("true")) {
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state)) {
context.put("back", "26");
} else {
context.put("back", "4");
}
return (String) getContext(data).get("template") + TEMPLATE[15];
case 16:
/*
* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[16];
case 17:
/*
* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished()) {
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
} else {
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[17];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state)) {
context.put("back", "26");
} else if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
/*
* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
/*
* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
/*
* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
/*
* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 23:
/*
* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null) {
state.setAttribute("form_joinable", new Boolean(site
.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null) {
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[23];
case 24:
/*
* buildContextForTemplate
* chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[24];
case 25:
/*
* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state
.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue()) {
// same role
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
} else {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[25];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
// titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null) {
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
// urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null) {
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null) {
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
// URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null) {
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
getToolsAvailableForImport(state))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
setTermListForContext(context, state, true); // true-> upcoming only
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true); // true -> upcoming only
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state
.getAttribute(SITE_MANUAL_COURSE_LIST));
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (!providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
/*
List list1 = prepareSectionObject(providerSectionList,
(String) state
.getAttribute(STATE_CM_CURRENT_USERID));
*/
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number - 1));
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("requestedSections", l);
}
// v2.4 - added & modified by daisyf
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "1");
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
// context.put("back", "36");
} else {
context.put("back", "1");
}
}
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
/*
* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
/*
* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
/*
* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
final List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
Object levelOpts[] = new Object[cmLevels.size()];
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
// populate options for dropdown lists
switch (numSelections) {
/*
* execution will fall through these statements based on number
* of selections already made
*/
case 3:
// intentionally blank
case 2:
levelOpts[2] = getCMSections((String) selections.get(1));
case 1:
levelOpts[1] = getCMCourseOfferings((String) selections
.get(0), t.getEid());
default:
levelOpts[0] = getCMSubjects();
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("requestedSections", requestedSections);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "36");
}
// else if (((String) state.getAttribute(STATE_SITE_MODE))
// .equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// context.put("backIndex", "");
// }
return (String) getContext(data).get("template") + TEMPLATE[53];
}
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
| private String buildContextForTemplate(int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
Site site = getStateSite(state);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
// the Grad Tools site option is only presented to
// GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a grad student?
if (!isGradToolsCandidate(userId)) {
// not a gradstudent
remove = true;
}
} catch (Exception e) {
remove = true;
}
} else {
// not support for dissertation sites
remove = true;
}
// do not show this site type in views
// sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
// the Grad Tools site option is only presented to UM grad
// students
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a UM grad student?
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
// if I am a UM grad student, do I already have a Grad Tools
// site?
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
if (Log.isWarnEnabled()) {
M_log.warn("buildContextForTemplate chef_site-type.vm "
+ e);
}
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) {
context.put("typeSelected", siteInfo.site_type);
} else if (types.size() > 0) {
context.put("typeSelected", types.get(0));
}
setTermListForContext(context, state, true); // true => only
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
/*
* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", siteType);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
context.put("back", "53");
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
context.put("back", "36");
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
} else {
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "0");
context.put("template-index", "37");
}
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put("back", "1");
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
/*
* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// ToolRegistrations
// for
// template
// list
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
// The "Home" tool checkbox needs special treatment to be selected
// by
// default.
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
/*
* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
// Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
// titles for news tools
context.put("newsTitles", state.getAttribute(STATE_NEWS_TITLES));
// titles for web content tools
context.put("wcTitles", state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// urls for news tools
context.put("newsUrls", state.getAttribute(STATE_NEWS_URLS));
// urls for web content tools
context.put("wcUrls", state.getAttribute(STATE_WEB_CONTENT_URLS));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
// get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
/*
* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
// Note that (for now) these strings are in both sakai.properties
// and sitesetupgeneric.properties
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName"));
context.put("noEmailInIdAccountLabel", ServerConfigurationService
.getString("noEmailInIdAccountLabel"));
context.put("emailInIdAccountName", ServerConfigurationService
.getString("emailInIdAccountName"));
context.put("emailInIdAccountLabel", ServerConfigurationService
.getString("emailInIdAccountLabel"));
if (state.getAttribute("noEmailInIdAccountValue") != null) {
context.put("noEmailInIdAccountValue", (String) state
.getAttribute("noEmailInIdAccountValue"));
}
if (state.getAttribute("emailInIdAccountValue") != null) {
context.put("emailInIdAccountValue", (String) state
.getAttribute("emailInIdAccountValue"));
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 6:
/*
* buildContextForTemplate chef_site-removeParticipants.vm
*
*/
context.put("title", site.getTitle());
realmId = SiteService.siteReference(site.getId());
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
try {
List removeableList = (List) state
.getAttribute(STATE_REMOVEABLE_USER_LIST);
List removeableParticipants = new Vector();
for (int k = 0; k < removeableList.size(); k++) {
User user = UserDirectoryService
.getUser((String) removeableList.get(k));
Participant participant = new Participant();
participant.name = user.getSortName();
participant.uniqname = user.getId();
Role r = realm.getUserRole(user.getId());
if (r != null) {
participant.role = r.getId();
}
removeableParticipants.add(participant);
}
context.put("removeableList", removeableParticipants);
} catch (UserNotDefinedException ee) {
}
} catch (GroupNotDefinedException e) {
}
context.put("backIndex", "18");
return (String) getContext(data).get("template") + TEMPLATE[6];
case 7:
/*
* buildContextForTemplate chef_site-changeRoles.vm
*
*/
context.put("same_role", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE));
roles = getRoles(state);
context.put("roles", roles);
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[7];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 9:
/*
* buildContextForTemplate chef_site-publishUnpublish.vm
*
*/
context.put("publish", Boolean.valueOf(((SiteInfo) state
.getAttribute(STATE_SITE_INFO)).getPublished()));
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[9];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 11:
/*
* buildContextForTemplate chef_site-newSitePublishUnpublish.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[11];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
if (allowUpdateSite) {
// top menu bar
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site access for GRADTOOLS
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals("course")) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site duplicate and import
// for GRADTOOLS type of sites
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
context.put("menu", b);
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
context.put("menu", b);
}
if (allowUpdateSiteMembership) {
// show add participant menu
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (!isMyWorkspace) {
// show the Add Participant menu
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
}
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
List participants = new Vector();
participants = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,
sortedAsc));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
context.put("participantListSize", new Integer(participants
.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
context.put("providerCourseList", providerCourseList);
}
String manualCourseListString = site.getProperties()
.getProperty(PROP_SITE_REQUEST_COURSE);
if (manualCourseListString != null) {
List manualCourseList = new Vector();
if (manualCourseListString.indexOf("+") != -1) {
manualCourseList = new ArrayList(
Arrays.asList(manualCourseListString
.split("\\+")));
} else {
manualCourseList.add(manualCourseListString);
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
context.put("manualCourseList", manualCourseList);
}
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
// put realm object into context
realmId = SiteService.siteReference(site.getId());
try {
context.put("realm", AuthzGroupService
.getAuthzGroup(realmId));
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + realmId);
}
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null) {
context.put("selectedIcon", state
.getAttribute(FORM_SITEINFO_SKIN));
} else if (site.getIconUrl() != null) {
context.put("selectedIcon", site.getIconUrl());
}
setTermListForContext(context, state, true); // true->only future terms
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
// Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with
// sakai.properties file.
if ((ServerConfigurationService
.getString("disable.course.site.skin.selection"))
.equals("true")) {
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("newsTitles", (Hashtable) state
.getAttribute(STATE_NEWS_TITLES));
context.put("wcTitles", (Hashtable) state
.getAttribute(STATE_WEB_CONTENT_TITLES));
if (fromENWModifyView(state)) {
context.put("back", "26");
} else {
context.put("back", "4");
}
return (String) getContext(data).get("template") + TEMPLATE[15];
case 16:
/*
* buildContextForTemplate chef_site-publishUnpublish-sendEmail.vm
*
*/
context.put("title", site.getTitle());
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[16];
case 17:
/*
* buildContextForTemplate chef_site-publishUnpublish-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("continueIndex", "12");
SiteInfo sInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (sInfo.getPublished()) {
context.put("publish", Boolean.TRUE);
context.put("backIndex", "16");
} else {
context.put("publish", Boolean.FALSE);
context.put("backIndex", "9");
}
context.put("willNotify", state.getAttribute(FORM_WILL_NOTIFY));
return (String) getContext(data).get("template") + TEMPLATE[17];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state)) {
context.put("back", "26");
} else if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
/*
* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
/*
* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
/*
* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
/*
* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 23:
/*
* buildContextForTemplate chef_siteInfo-editAccess-globalAccess.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
if (state.getAttribute("form_joinable") == null) {
state.setAttribute("form_joinable", new Boolean(site
.isJoinable()));
}
context.put("form_joinable", state.getAttribute("form_joinable"));
if (state.getAttribute("form_joinerRole") == null) {
state.setAttribute("form_joinerRole", site.getJoinerRole());
}
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[23];
case 24:
/*
* buildContextForTemplate
* chef_siteInfo-editAccess-globalAccess-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("form_joinable", state.getAttribute("form_joinable"));
context.put("form_joinerRole", state
.getAttribute("form_joinerRole"));
return (String) getContext(data).get("template") + TEMPLATE[24];
case 25:
/*
* buildContextForTemplate chef_changeRoles-confirm.vm
*
*/
Boolean sameRole = (Boolean) state
.getAttribute(STATE_CHANGEROLE_SAMEROLE);
context.put("sameRole", sameRole);
if (sameRole.booleanValue()) {
// same role
context.put("currentRole", state
.getAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE));
} else {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
roles = getRoles(state);
context.put("roles", roles);
context.put("participantSelectedList", state
.getAttribute(STATE_SELECTED_PARTICIPANTS));
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) != null) {
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
}
context.put("siteTitle", site.getTitle());
return (String) getContext(data).get("template") + TEMPLATE[25];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
// titles for news tools
newsTitles = (Hashtable) state.getAttribute(STATE_NEWS_TITLES);
if (newsTitles == null) {
newsTitles = new Hashtable();
newsTitles.put("sakai.news", NEWS_DEFAULT_TITLE);
state.setAttribute(STATE_NEWS_TITLES, newsTitles);
}
context.put("newsTitles", newsTitles);
// urls for news tools
newsUrls = (Hashtable) state.getAttribute(STATE_NEWS_URLS);
if (newsUrls == null) {
newsUrls = new Hashtable();
newsUrls.put("sakai.news", NEWS_DEFAULT_URL);
state.setAttribute(STATE_NEWS_URLS, newsUrls);
}
context.put("newsUrls", newsUrls);
// titles for web content tools
wcTitles = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_TITLES);
if (wcTitles == null) {
wcTitles = new Hashtable();
wcTitles.put("sakai.iframe", WEB_CONTENT_DEFAULT_TITLE);
state.setAttribute(STATE_WEB_CONTENT_TITLES, wcTitles);
}
context.put("wcTitles", wcTitles);
// URLs for web content tools
wcUrls = (Hashtable) state.getAttribute(STATE_WEB_CONTENT_URLS);
if (wcUrls == null) {
wcUrls = new Hashtable();
wcUrls.put("sakai.iframe", WEB_CONTENT_DEFAULT_URL);
state.setAttribute(STATE_WEB_CONTENT_URLS, wcUrls);
}
context.put("wcUrls", wcUrls);
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
(List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals("course")) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
setTermListForContext(context, state, true); // true-> upcoming only
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true); // true -> upcoming only
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
context.put("providerCourseList", providerCourseList);
context.put("manualCourseList", state
.getAttribute(SITE_MANUAL_COURSE_LIST));
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (!providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
/*
List list1 = prepareSectionObject(providerSectionList,
(String) state
.getAttribute(STATE_CM_CURRENT_USERID));
*/
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("noEmailInIdAccountName", ServerConfigurationService
.getString("noEmailInIdAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", new Integer(number - 1));
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("requestedSections", l);
}
// v2.4 - added & modified by daisyf
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "1");
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
// context.put("back", "36");
} else {
context.put("back", "1");
}
}
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
/*
* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
/*
* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
/*
* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
final List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
Object levelOpts[] = new Object[cmLevels.size()];
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
// populate options for dropdown lists
switch (numSelections) {
/*
* execution will fall through these statements based on number
* of selections already made
*/
case 3:
// intentionally blank
case 2:
levelOpts[2] = getCMSections((String) selections.get(1));
case 1:
levelOpts[1] = getCMCourseOfferings((String) selections
.get(0), t.getEid());
default:
levelOpts[0] = getCMSubjects();
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("requestedSections", requestedSections);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "36");
}
// else if (((String) state.getAttribute(STATE_SITE_MODE))
// .equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// context.put("backIndex", "");
// }
return (String) getContext(data).get("template") + TEMPLATE[53];
}
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
|
diff --git a/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java b/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
index 0fdd6ce..6833edf 100644
--- a/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
+++ b/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
@@ -1,222 +1,224 @@
/**
* taskwarrior for android – a task list manager
*
* Copyright (c) 2012 Sujeevan Vijayakumaran
* 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
* allcopies 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.
*
* http://www.opensource.org/licenses/mit-license.php
*
*/
package org.svij.taskwarriorapp.db;
import java.text.DateFormat;
import java.util.ArrayList;
import org.svij.taskwarriorapp.R;
import org.svij.taskwarriorapp.data.Task;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class TaskBaseAdapter extends BaseAdapter {
private ArrayList<Task> entries;
private Activity activity;
private static final int TYPE_ROW = 0;
private static final int TYPE_ROW_CLICKED = 1;
private static final int TYPE_MAX_COUNT = TYPE_ROW_CLICKED + 1;
private ArrayList<Integer> RowClickedList = new ArrayList<Integer>();
private Context context;
public TaskBaseAdapter(Activity a, int layoutID, ArrayList<Task> entries,
Context context) {
super();
this.entries = entries;
this.activity = a;
this.context = context;
}
public static class ViewHolder {
public TextView taskDescription;
public TextView taskProject;
public TextView taskDueDate;
public TextView taskPriority;
public TextView taskStatus;
public TextView taskUrgency;
public RelativeLayout taskRelLayout;
public FrameLayout taskFramelayout;
public View taskPriorityView;
}
public void changeTaskRow(final int position) {
if (RowClickedList.contains(position)) {
RowClickedList.remove(Integer.valueOf(position));
} else {
RowClickedList.add(position);
}
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String textAppearance = prefs
.getString(
"pref_appearance_descriptionTextSize",
context.getResources()
.getString(
R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_large));
}
if (task.getProject() != null) {
+ holder.taskProject.setVisibility(View.VISIBLE);
holder.taskProject.setText(task.getProject());
} else {
holder.taskProject.setVisibility(View.GONE);
}
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
+ holder.taskDueDate.setVisibility(View.VISIBLE);
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(android.R.color.transparent));
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
@Override
public int getItemViewType(int position) {
return RowClickedList.contains(position) ? TYPE_ROW_CLICKED : TYPE_ROW;
}
@Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
@Override
public int getCount() {
return entries.size();
}
@Override
public Object getItem(int position) {
return entries.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String textAppearance = prefs
.getString(
"pref_appearance_descriptionTextSize",
context.getResources()
.getString(
R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_large));
}
if (task.getProject() != null) {
holder.taskProject.setText(task.getProject());
} else {
holder.taskProject.setVisibility(View.GONE);
}
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(android.R.color.transparent));
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String textAppearance = prefs
.getString(
"pref_appearance_descriptionTextSize",
context.getResources()
.getString(
R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(
R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources()
.getDimension(R.dimen.taskDescription_large));
}
if (task.getProject() != null) {
holder.taskProject.setVisibility(View.VISIBLE);
holder.taskProject.setText(task.getProject());
} else {
holder.taskProject.setVisibility(View.GONE);
}
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
holder.taskDueDate.setVisibility(View.VISIBLE);
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(android.R.color.transparent));
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
|
diff --git a/src/main/java/net/krinsoft/jobsuite/commands/JobAddItemCommand.java b/src/main/java/net/krinsoft/jobsuite/commands/JobAddItemCommand.java
index d5bc882..aee4e48 100644
--- a/src/main/java/net/krinsoft/jobsuite/commands/JobAddItemCommand.java
+++ b/src/main/java/net/krinsoft/jobsuite/commands/JobAddItemCommand.java
@@ -1,81 +1,84 @@
package net.krinsoft.jobsuite.commands;
import net.krinsoft.jobsuite.Job;
import net.krinsoft.jobsuite.JobCore;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
* @author krinsdeath
*/
public class JobAddItemCommand extends JobCommand {
public JobAddItemCommand(JobCore instance) {
super(instance);
setName("JobSuite: Add Item");
setCommandUsage("/job additem [type[:data]] [amount]");
addCommandExample("/job additem stone 64 -- Request 64 stone");
addCommandExample("/job additem 17:1 32 -- Request 32 pine wood logs");
addCommandExample("/job additem 263:1 64 -- Request 64 charcoal");
setArgRange(2, 2);
addKey("jobsuite additem");
addKey("job additem");
addKey("js additem");
addKey("jobsuite ai");
addKey("job ai");
addKey("js ai");
setPermission("jobsuite.additem", "Adds a required job item.", PermissionDefault.TRUE);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
Job job = manager.getQueuedJob(sender.getName());
if (job != null) {
Material type;
byte data = 0;
try {
String arg = args.get(0);
if (arg.contains(":")) {
arg = args.get(0).split(":")[0];
data = Byte.parseByte(args.get(0).split(":")[1]);
}
type = Material.getMaterial(Integer.parseInt(arg));
} catch (NumberFormatException e) {
type = Material.matchMaterial(args.get(0));
} catch (ArrayIndexOutOfBoundsException e) {
error(sender, "Something went wrong with your input.");
return;
}
if (type == null) {
error(sender, "Unknown item type.");
return;
}
+ if (type == Material.PISTON_STICKY_BASE) {
+ data = 7;
+ }
int amount;
try {
amount = Integer.parseInt(args.get(1));
} catch (NumberFormatException e) {
error(sender, "Error parsing argument: expected number");
return;
}
if (type.getMaxStackSize() < amount) {
error(sender, "Please split the items up into multiple entries.");
return;
}
ItemStack item = new ItemStack(type, amount, (short) 0, data);
int id = job.addItem(item);
- message(sender, "Item added at index '" + id + "'");
+ message(sender, "Item added at index '" + id + "': " + item.getType().toString());
message(sender, "View item info: " + ChatColor.DARK_AQUA + "/job info this " + id);
message(sender, "Add an enchantment: " + ChatColor.DARK_AQUA + "/job addenchant " + id + " [enchantment] [level]");
message(sender, "Remove this item: " + ChatColor.DARK_AQUA + "/job remitem " + id);
message(sender, "Add more items: " + ChatColor.DARK_AQUA + "/job additem [type] [amount]");
message(sender, "Post the job: " + ChatColor.GOLD + "/job post");
} else {
error(sender, "You aren't currently making a job.");
}
}
}
| false | true | public void runCommand(CommandSender sender, List<String> args) {
Job job = manager.getQueuedJob(sender.getName());
if (job != null) {
Material type;
byte data = 0;
try {
String arg = args.get(0);
if (arg.contains(":")) {
arg = args.get(0).split(":")[0];
data = Byte.parseByte(args.get(0).split(":")[1]);
}
type = Material.getMaterial(Integer.parseInt(arg));
} catch (NumberFormatException e) {
type = Material.matchMaterial(args.get(0));
} catch (ArrayIndexOutOfBoundsException e) {
error(sender, "Something went wrong with your input.");
return;
}
if (type == null) {
error(sender, "Unknown item type.");
return;
}
int amount;
try {
amount = Integer.parseInt(args.get(1));
} catch (NumberFormatException e) {
error(sender, "Error parsing argument: expected number");
return;
}
if (type.getMaxStackSize() < amount) {
error(sender, "Please split the items up into multiple entries.");
return;
}
ItemStack item = new ItemStack(type, amount, (short) 0, data);
int id = job.addItem(item);
message(sender, "Item added at index '" + id + "'");
message(sender, "View item info: " + ChatColor.DARK_AQUA + "/job info this " + id);
message(sender, "Add an enchantment: " + ChatColor.DARK_AQUA + "/job addenchant " + id + " [enchantment] [level]");
message(sender, "Remove this item: " + ChatColor.DARK_AQUA + "/job remitem " + id);
message(sender, "Add more items: " + ChatColor.DARK_AQUA + "/job additem [type] [amount]");
message(sender, "Post the job: " + ChatColor.GOLD + "/job post");
} else {
error(sender, "You aren't currently making a job.");
}
}
| public void runCommand(CommandSender sender, List<String> args) {
Job job = manager.getQueuedJob(sender.getName());
if (job != null) {
Material type;
byte data = 0;
try {
String arg = args.get(0);
if (arg.contains(":")) {
arg = args.get(0).split(":")[0];
data = Byte.parseByte(args.get(0).split(":")[1]);
}
type = Material.getMaterial(Integer.parseInt(arg));
} catch (NumberFormatException e) {
type = Material.matchMaterial(args.get(0));
} catch (ArrayIndexOutOfBoundsException e) {
error(sender, "Something went wrong with your input.");
return;
}
if (type == null) {
error(sender, "Unknown item type.");
return;
}
if (type == Material.PISTON_STICKY_BASE) {
data = 7;
}
int amount;
try {
amount = Integer.parseInt(args.get(1));
} catch (NumberFormatException e) {
error(sender, "Error parsing argument: expected number");
return;
}
if (type.getMaxStackSize() < amount) {
error(sender, "Please split the items up into multiple entries.");
return;
}
ItemStack item = new ItemStack(type, amount, (short) 0, data);
int id = job.addItem(item);
message(sender, "Item added at index '" + id + "': " + item.getType().toString());
message(sender, "View item info: " + ChatColor.DARK_AQUA + "/job info this " + id);
message(sender, "Add an enchantment: " + ChatColor.DARK_AQUA + "/job addenchant " + id + " [enchantment] [level]");
message(sender, "Remove this item: " + ChatColor.DARK_AQUA + "/job remitem " + id);
message(sender, "Add more items: " + ChatColor.DARK_AQUA + "/job additem [type] [amount]");
message(sender, "Post the job: " + ChatColor.GOLD + "/job post");
} else {
error(sender, "You aren't currently making a job.");
}
}
|
diff --git a/src/edu/uw/cs/lil/tiny/tempeval/TempEval3Dev.java b/src/edu/uw/cs/lil/tiny/tempeval/TempEval3Dev.java
index 1c9e06ec..9cc6ce1f 100644
--- a/src/edu/uw/cs/lil/tiny/tempeval/TempEval3Dev.java
+++ b/src/edu/uw/cs/lil/tiny/tempeval/TempEval3Dev.java
@@ -1,437 +1,437 @@
package edu.uw.cs.lil.tiny.tempeval;
import edu.uw.cs.lil.learn.simple.joint.JointSimplePerceptron;
import edu.uw.cs.lil.tiny.ccg.categories.ICategoryServices;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.ComplexSyntax;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.Slash;
import edu.uw.cs.lil.tiny.ccg.categories.syntax.Syntax;
import edu.uw.cs.lil.tiny.data.IDataCollection;
import edu.uw.cs.lil.tiny.data.ILabeledDataItem;
import edu.uw.cs.lil.tiny.data.sentence.Sentence;
import edu.uw.cs.lil.tiny.learn.ILearner;
import edu.uw.cs.lil.tiny.mr.lambda.FlexibleTypeComparator;
import edu.uw.cs.lil.tiny.mr.lambda.LogicLanguageServices;
import edu.uw.cs.lil.tiny.mr.lambda.LogicalExpression;
import edu.uw.cs.lil.tiny.mr.lambda.Ontology;
import edu.uw.cs.lil.tiny.mr.lambda.ccg.LogicalExpressionCategoryServices;
import edu.uw.cs.lil.tiny.mr.lambda.ccg.SimpleFullParseFilter;
import edu.uw.cs.lil.tiny.mr.language.type.TypeRepository;
import edu.uw.cs.lil.tiny.parser.ccg.cky.AbstractCKYParser;
import edu.uw.cs.lil.tiny.parser.ccg.cky.CKYBinaryParsingRule;
import edu.uw.cs.lil.tiny.parser.ccg.cky.multi.MultiCKYParser;
import edu.uw.cs.lil.tiny.parser.ccg.cky.single.CKYParser;
import edu.uw.cs.lil.tiny.parser.ccg.cky.single.CKYUnaryParsingRule;
import edu.uw.cs.lil.tiny.parser.ccg.factoredlex.FactoredLexicon;
import edu.uw.cs.lil.tiny.parser.ccg.factoredlex.Lexeme;
import edu.uw.cs.lil.tiny.parser.ccg.factoredlex.features.LexemeFeatureSet;
import edu.uw.cs.lil.tiny.parser.ccg.factoredlex.features.LexicalTemplateFeatureSet;
import edu.uw.cs.lil.tiny.parser.ccg.factoredlex.features.scorers.LexemeCooccurrenceScorer;
import edu.uw.cs.lil.tiny.parser.ccg.features.basic.LexicalFeatureSet;
import edu.uw.cs.lil.tiny.parser.ccg.features.basic.scorer.ExpLengthLexicalEntryScorer;
import edu.uw.cs.lil.tiny.parser.ccg.features.basic.scorer.ScalingScorer;
import edu.uw.cs.lil.tiny.parser.ccg.features.basic.scorer.SkippingSensitiveLexicalEntryScorer;
import edu.uw.cs.lil.tiny.parser.ccg.features.basic.scorer.UniformScorer;
import edu.uw.cs.lil.tiny.parser.ccg.features.lambda.LogicalExpressionCoordinationFeatureSet;
import edu.uw.cs.lil.tiny.parser.ccg.features.lambda.LogicalExpressionTypeFeatureSet;
import edu.uw.cs.lil.tiny.parser.ccg.lexicon.ILexicon;
import edu.uw.cs.lil.tiny.parser.ccg.lexicon.LexicalEntry;
//import edu.uw.cs.lil.tiny.parser.ccg.lexicon.LexicalEntry.EntryOrigin;
import edu.uw.cs.lil.tiny.parser.ccg.lexicon.Lexicon;
import edu.uw.cs.lil.tiny.parser.ccg.model.Model;
import edu.uw.cs.lil.tiny.parser.ccg.rules.RuleSetBuilder;
import edu.uw.cs.lil.tiny.parser.ccg.rules.primitivebinary.BackwardApplication;
import edu.uw.cs.lil.tiny.parser.ccg.rules.primitivebinary.BackwardComposition;
import edu.uw.cs.lil.tiny.parser.ccg.rules.primitivebinary.ForwardApplication;
import edu.uw.cs.lil.tiny.parser.ccg.rules.primitivebinary.ForwardComposition;
import edu.uw.cs.lil.tiny.parser.ccg.rules.skipping.BackwardSkippingRule;
import edu.uw.cs.lil.tiny.parser.ccg.rules.skipping.ForwardSkippingRule;
import edu.uw.cs.lil.tiny.parser.joint.model.JointDataItemModel;
import edu.uw.cs.lil.tiny.parser.joint.model.JointModel;
import edu.uw.cs.lil.tiny.tempeval.featureSets.TemporalContextFeatureSet;
import edu.uw.cs.lil.tiny.tempeval.featureSets.TemporalDayOfWeekFeatureSet;
import edu.uw.cs.lil.tiny.tempeval.featureSets.TemporalReferenceFeatureSet;
import edu.uw.cs.lil.tiny.tempeval.featureSets.TemporalTypeFeatureSet;
import edu.uw.cs.lil.tiny.utils.concurrency.TinyExecutorService;
import edu.uw.cs.lil.tiny.utils.string.StubStringFilter;
import edu.uw.cs.utils.composites.Pair;
import edu.uw.cs.utils.log.ILogger;
import edu.uw.cs.utils.log.Log;
import edu.uw.cs.utils.log.LogLevel;
import edu.uw.cs.utils.log.Logger;
import edu.uw.cs.utils.log.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class TempEval3Dev {
private static final ILogger LOG = LoggerFactory.create(TempEval3Dev.class);
public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean readSerializedDatasets = false; // this takes precedence over booleans testingDataset, timebank, and crossVal.
boolean serializeDatasets = false;
boolean testingDataset = true; // testing dataset takes precidenence over timebank
// options for dataSetName: "tempeval3.aquaintAndTimebank.txt", "tempeval3.aquaint.txt", "tempeval3.timebank.txt"
String dataSetName = "tempeval3.aquaintAndTimebank.txt";
- boolean crossVal = false;
+ boolean crossVal = true;
int numIterations = 1;
Logger.DEFAULT_LOG = new Log(System.out);
Logger.setSkipPrefix(true);
LogLevel.INFO.set();
//long startTime = System.currentTimeMillis();
// Relative path for data directories
String datasetDir = "./data/dataset/";
String resourcesDir = "./data/resources/";
// Init the logical expression type system
// LogicLanguageServices.setInstance(new LogicLanguageServices(
// new TypeRepository(
// new File(resourcesDir + "tempeval.types.txt")), "i"));
LogicLanguageServices.setInstance(new LogicLanguageServices.Builder(
new TypeRepository(new File(resourcesDir + "tempeval.types.txt"))).setNumeralTypeName("i")
.setTypeComparator(new FlexibleTypeComparator()).build());
final ICategoryServices<LogicalExpression> categoryServices = new LogicalExpressionCategoryServices();
// Load the ontology
List<File> ontologyFiles = new LinkedList<File>();
ontologyFiles.add(new File(resourcesDir + "tempeval.predicates.txt"));
ontologyFiles.add(new File(resourcesDir + "tempeval.constants.txt"));
try {
// Ontology is currently not used, so we are just reading it, not
// storing
new Ontology(ontologyFiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
// When running on testing dataset, testingDataset = true
String dataLoc;
if (testingDataset)
dataLoc = "tempeval3.testing.txt";
else{
dataLoc = dataSetName;
}
//dataLoc = "tempeval.dataset.corrected.txt";
// these train and test should be of type
// IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, Pair<String, String>>>
TemporalSentenceDataset train = null;
TemporalSentenceDataset test = null;
// reading in the serialized datasets so we don't have to run the dependency parser again.
if (readSerializedDatasets){
train = TemporalSentenceDataset.readSerialized("data/serialized_data/trainingData.ser");
test = TemporalSentenceDataset.readSerialized("data/serialized_data/testingData.ser");
} else {
train = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
test = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
}
if (serializeDatasets){
System.out.print("Serializing the training data... ");
TemporalSentenceDataset.save("data/serialized_data/trainingData.ser", train);
System.out.println("Done!");
System.out.print("Serializing the testing data... ");
TemporalSentenceDataset.save("data/serialized_data/testingData.ser", test);
System.out.println("Done!");
}
LOG.info("Train Size: " + train.size());
LOG.info("Test Size: " + test.size());
// Below is the code from Geo880DevParameterEstimation. I am replacing this with code from Geo880Dev.
/*
// Init the lexicon
final ILexicon<LogicalExpression> lexicon = new Lexicon<LogicalExpression>();
lexicon.addEntriesFromFile(
new File(
resourcesDir + "tempeval.lexicon.txt"),
new StubStringFilter(), categoryServices,
EntryOrigin.FIXED_DOMAIN);
LOG.info("Size of lexicon: %d", lexicon.size());
LOG.info("Size of lexicon: %d", lexicon.size());
final LexicalFeatureSet<LogicalExpression> lexPhi = new LexicalFeatureSetBuilder<LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0))).build();
// Create the model
final Model<Sentence, LogicalExpression> model = new Model.Builder<Sentence, LogicalExpression>()
.addParseFeatureSet(
new LogicalExpressionCoordinationFeatureSet<Sentence>())
.addParseFeatureSet(
new LogicalExpressionTypeFeatureSet<Sentence>())
.addLexicalFeatureSet(lexPhi)
.setLexicon(new Lexicon<LogicalExpression>()).build();
*/
// Init the lexicon
// final Lexicon<LogicalExpression> fixed = new
// Lexicon<LogicalExpression>();
final ILexicon<LogicalExpression> fixedInput = new Lexicon<LogicalExpression>();
fixedInput.addEntriesFromFile(new File(resourcesDir
+ "tempeval.lexicon.txt"), new StubStringFilter(),
categoryServices, LexicalEntry.Origin.FIXED_DOMAIN);
final ILexicon<LogicalExpression> fixed = new Lexicon<LogicalExpression>();
// factor the fixed lexical entries
//for (final LexicalEntry<LogicalExpression> lex : fixedInput
// .toCollection()) {
// fixed.add(FactoredLexicon.factor(lex));
//}
//System.out.println(fixed);
// try two at factoring the fixed lexical entries:
for (final LexicalEntry<LogicalExpression> lex : fixedInput.toCollection()){
fixed.add(lex);
}
final LexicalFeatureSet<Sentence, LogicalExpression> lexPhi = new LexicalFeatureSet.Builder<Sentence,LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0)))
// .setInitialWeightScorer(gizaScores)
.build();
// Create the lexeme feature set
//final LexemeCooccurrenceScorer gizaScores;
// final DecoderHelper<LogicalExpression> decoderHelper = new
// DecoderHelper<LogicalExpression>(
// categoryServices);
//try {
// gizaScores = new LexemeCooccurrenceScorer(new File(resourcesDir
// + "/geo600.dev.giza_probs"));
//} catch (final IOException e) {
// System.err.println(e);
// throw new RuntimeException(e);
//}
//final LexemeFeatureSet lexemeFeats = new LexemeFeatureSet.Builder()
// .setInitialFixedScorer(new UniformScorer<Lexeme>(0.0))
// .setInitialScorer(new ScalingScorer<Lexeme>(10.0, gizaScores))
// .build();
// This was used for initializing the factored lexicon
final LexicalTemplateFeatureSet templateFeats = new LexicalTemplateFeatureSet.Builder()
.setScale(0.1)
// .setInitialWeightScorer(new LexicalSyntaxPenaltyScorer(-0.1))
.build();
// Create the entire feature collection
// Adjusted to move away from a factored lexicon
// Parsing rules
final RuleSetBuilder<LogicalExpression> ruleSetBuilder = new RuleSetBuilder<LogicalExpression>();
// Binary rules
ruleSetBuilder.add(new ForwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new ForwardApplication<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardApplication<LogicalExpression>(
categoryServices));
// Executor for multi-threading
final TinyExecutorService executor = new TinyExecutorService(Runtime
.getRuntime().availableProcessors());
LOG.info("Using %d threads", Runtime.getRuntime().availableProcessors());
final Set<Syntax> syntaxSet = new HashSet<Syntax>();
syntaxSet.add(Syntax.NP);
final SimpleFullParseFilter<LogicalExpression> parseFilter = new SimpleFullParseFilter<LogicalExpression>(
syntaxSet);
final AbstractCKYParser<LogicalExpression> parser = new CKYParser.Builder<LogicalExpression>(
categoryServices, parseFilter)//, executor)
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
ruleSetBuilder.build()))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new ForwardSkippingRule<LogicalExpression>(
categoryServices)))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new BackwardSkippingRule<LogicalExpression>(
categoryServices)))
.setMaxNumberOfCellsInSpan(100).build();
// Crossvalidation starts here.
if (crossVal){
double numberOfPartitions = 3.0;
// make a list
// use the constructor with TemporalSentenceDataset to make a new dataset.
System.out.println("Splitting the data...");
List<List<TemporalSentence>> splitData =
new LinkedList<List<TemporalSentence>>();
Iterator<TemporalSentence> iter = train.iterator();
int sentenceCount = 1;
List<TemporalSentence> tmp =
new LinkedList<TemporalSentence>();
while (iter.hasNext()){
tmp.add(iter.next());
// for testing:
if (sentenceCount % Math.round(train.size() / numberOfPartitions)== 0){
splitData.add(tmp);
tmp = new LinkedList<TemporalSentence>();
System.out.println();
System.out.println("sentenceCount: " + sentenceCount);
System.out.println("Train size: " + train.size());
System.out.println("size / " + numberOfPartitions + ": " + Math.round(train.size() / numberOfPartitions));
}
sentenceCount++;
}
System.out.println(" done.");
OutputData[] outList = new OutputData[splitData.size()];
// to make the threads
TemporalThread[] threads = new TemporalThread[splitData.size()];
for (int i = 0; i < splitData.size(); i++){
// to make the training and testing corpora
List<TemporalSentence> newTrainList = new LinkedList<TemporalSentence>();
List<TemporalSentence> newTestList = new LinkedList<TemporalSentence>();
for (int j = 0; j < splitData.size(); j++){
if (i == j)
newTestList.addAll(splitData.get(i));
else
newTrainList.addAll(splitData.get(j));
}
// to make them into IDataCollection items:
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTest =
new TemporalSentenceDataset(newTestList);
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTrain =
new TemporalSentenceDataset(newTrainList);
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final TemporalTesterSmall tester = TemporalTesterSmall.build(newTest, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner =
new JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, newTrain, jParser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
OutputData outputData = new OutputData();
threads[i] = new TemporalThread(learner, tester, i, outputData, model);
threads[i].start();
outList[i] = outputData;
}
for (int i = 0; i < threads.length; i++){
try{
threads[i].join();
} catch (InterruptedException e){
e.printStackTrace();
System.err.println("Some problems getting the threads to join again!");
}
}
PrintStream out = new PrintStream(new File("output/totals.txt"));
OutputData averaged = OutputData.average(outList);
out.println(averaged);
out.close();
// Not crossval
} else {
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
final TemporalTesterSmall tester = TemporalTesterSmall.build(test, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner = new
JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, train, jParser);
learner.train(model);
// Within this tester, I should go through each example and use the
// visitor on each logical expression!
OutputData o = new OutputData();
tester.test(model, System.out,o);
}
//LOG.info("Total runtime %.4f seconds", Double.valueOf(System
// .currentTimeMillis() - startTime / 1000.0D));
}
}
| true | true | public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean readSerializedDatasets = false; // this takes precedence over booleans testingDataset, timebank, and crossVal.
boolean serializeDatasets = false;
boolean testingDataset = true; // testing dataset takes precidenence over timebank
// options for dataSetName: "tempeval3.aquaintAndTimebank.txt", "tempeval3.aquaint.txt", "tempeval3.timebank.txt"
String dataSetName = "tempeval3.aquaintAndTimebank.txt";
boolean crossVal = false;
int numIterations = 1;
Logger.DEFAULT_LOG = new Log(System.out);
Logger.setSkipPrefix(true);
LogLevel.INFO.set();
//long startTime = System.currentTimeMillis();
// Relative path for data directories
String datasetDir = "./data/dataset/";
String resourcesDir = "./data/resources/";
// Init the logical expression type system
// LogicLanguageServices.setInstance(new LogicLanguageServices(
// new TypeRepository(
// new File(resourcesDir + "tempeval.types.txt")), "i"));
LogicLanguageServices.setInstance(new LogicLanguageServices.Builder(
new TypeRepository(new File(resourcesDir + "tempeval.types.txt"))).setNumeralTypeName("i")
.setTypeComparator(new FlexibleTypeComparator()).build());
final ICategoryServices<LogicalExpression> categoryServices = new LogicalExpressionCategoryServices();
// Load the ontology
List<File> ontologyFiles = new LinkedList<File>();
ontologyFiles.add(new File(resourcesDir + "tempeval.predicates.txt"));
ontologyFiles.add(new File(resourcesDir + "tempeval.constants.txt"));
try {
// Ontology is currently not used, so we are just reading it, not
// storing
new Ontology(ontologyFiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
// When running on testing dataset, testingDataset = true
String dataLoc;
if (testingDataset)
dataLoc = "tempeval3.testing.txt";
else{
dataLoc = dataSetName;
}
//dataLoc = "tempeval.dataset.corrected.txt";
// these train and test should be of type
// IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, Pair<String, String>>>
TemporalSentenceDataset train = null;
TemporalSentenceDataset test = null;
// reading in the serialized datasets so we don't have to run the dependency parser again.
if (readSerializedDatasets){
train = TemporalSentenceDataset.readSerialized("data/serialized_data/trainingData.ser");
test = TemporalSentenceDataset.readSerialized("data/serialized_data/testingData.ser");
} else {
train = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
test = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
}
if (serializeDatasets){
System.out.print("Serializing the training data... ");
TemporalSentenceDataset.save("data/serialized_data/trainingData.ser", train);
System.out.println("Done!");
System.out.print("Serializing the testing data... ");
TemporalSentenceDataset.save("data/serialized_data/testingData.ser", test);
System.out.println("Done!");
}
LOG.info("Train Size: " + train.size());
LOG.info("Test Size: " + test.size());
// Below is the code from Geo880DevParameterEstimation. I am replacing this with code from Geo880Dev.
/*
// Init the lexicon
final ILexicon<LogicalExpression> lexicon = new Lexicon<LogicalExpression>();
lexicon.addEntriesFromFile(
new File(
resourcesDir + "tempeval.lexicon.txt"),
new StubStringFilter(), categoryServices,
EntryOrigin.FIXED_DOMAIN);
LOG.info("Size of lexicon: %d", lexicon.size());
LOG.info("Size of lexicon: %d", lexicon.size());
final LexicalFeatureSet<LogicalExpression> lexPhi = new LexicalFeatureSetBuilder<LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0))).build();
// Create the model
final Model<Sentence, LogicalExpression> model = new Model.Builder<Sentence, LogicalExpression>()
.addParseFeatureSet(
new LogicalExpressionCoordinationFeatureSet<Sentence>())
.addParseFeatureSet(
new LogicalExpressionTypeFeatureSet<Sentence>())
.addLexicalFeatureSet(lexPhi)
.setLexicon(new Lexicon<LogicalExpression>()).build();
*/
// Init the lexicon
// final Lexicon<LogicalExpression> fixed = new
// Lexicon<LogicalExpression>();
final ILexicon<LogicalExpression> fixedInput = new Lexicon<LogicalExpression>();
fixedInput.addEntriesFromFile(new File(resourcesDir
+ "tempeval.lexicon.txt"), new StubStringFilter(),
categoryServices, LexicalEntry.Origin.FIXED_DOMAIN);
final ILexicon<LogicalExpression> fixed = new Lexicon<LogicalExpression>();
// factor the fixed lexical entries
//for (final LexicalEntry<LogicalExpression> lex : fixedInput
// .toCollection()) {
// fixed.add(FactoredLexicon.factor(lex));
//}
//System.out.println(fixed);
// try two at factoring the fixed lexical entries:
for (final LexicalEntry<LogicalExpression> lex : fixedInput.toCollection()){
fixed.add(lex);
}
final LexicalFeatureSet<Sentence, LogicalExpression> lexPhi = new LexicalFeatureSet.Builder<Sentence,LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0)))
// .setInitialWeightScorer(gizaScores)
.build();
// Create the lexeme feature set
//final LexemeCooccurrenceScorer gizaScores;
// final DecoderHelper<LogicalExpression> decoderHelper = new
// DecoderHelper<LogicalExpression>(
// categoryServices);
//try {
// gizaScores = new LexemeCooccurrenceScorer(new File(resourcesDir
// + "/geo600.dev.giza_probs"));
//} catch (final IOException e) {
// System.err.println(e);
// throw new RuntimeException(e);
//}
//final LexemeFeatureSet lexemeFeats = new LexemeFeatureSet.Builder()
// .setInitialFixedScorer(new UniformScorer<Lexeme>(0.0))
// .setInitialScorer(new ScalingScorer<Lexeme>(10.0, gizaScores))
// .build();
// This was used for initializing the factored lexicon
final LexicalTemplateFeatureSet templateFeats = new LexicalTemplateFeatureSet.Builder()
.setScale(0.1)
// .setInitialWeightScorer(new LexicalSyntaxPenaltyScorer(-0.1))
.build();
// Create the entire feature collection
// Adjusted to move away from a factored lexicon
// Parsing rules
final RuleSetBuilder<LogicalExpression> ruleSetBuilder = new RuleSetBuilder<LogicalExpression>();
// Binary rules
ruleSetBuilder.add(new ForwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new ForwardApplication<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardApplication<LogicalExpression>(
categoryServices));
// Executor for multi-threading
final TinyExecutorService executor = new TinyExecutorService(Runtime
.getRuntime().availableProcessors());
LOG.info("Using %d threads", Runtime.getRuntime().availableProcessors());
final Set<Syntax> syntaxSet = new HashSet<Syntax>();
syntaxSet.add(Syntax.NP);
final SimpleFullParseFilter<LogicalExpression> parseFilter = new SimpleFullParseFilter<LogicalExpression>(
syntaxSet);
final AbstractCKYParser<LogicalExpression> parser = new CKYParser.Builder<LogicalExpression>(
categoryServices, parseFilter)//, executor)
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
ruleSetBuilder.build()))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new ForwardSkippingRule<LogicalExpression>(
categoryServices)))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new BackwardSkippingRule<LogicalExpression>(
categoryServices)))
.setMaxNumberOfCellsInSpan(100).build();
// Crossvalidation starts here.
if (crossVal){
double numberOfPartitions = 3.0;
// make a list
// use the constructor with TemporalSentenceDataset to make a new dataset.
System.out.println("Splitting the data...");
List<List<TemporalSentence>> splitData =
new LinkedList<List<TemporalSentence>>();
Iterator<TemporalSentence> iter = train.iterator();
int sentenceCount = 1;
List<TemporalSentence> tmp =
new LinkedList<TemporalSentence>();
while (iter.hasNext()){
tmp.add(iter.next());
// for testing:
if (sentenceCount % Math.round(train.size() / numberOfPartitions)== 0){
splitData.add(tmp);
tmp = new LinkedList<TemporalSentence>();
System.out.println();
System.out.println("sentenceCount: " + sentenceCount);
System.out.println("Train size: " + train.size());
System.out.println("size / " + numberOfPartitions + ": " + Math.round(train.size() / numberOfPartitions));
}
sentenceCount++;
}
System.out.println(" done.");
OutputData[] outList = new OutputData[splitData.size()];
// to make the threads
TemporalThread[] threads = new TemporalThread[splitData.size()];
for (int i = 0; i < splitData.size(); i++){
// to make the training and testing corpora
List<TemporalSentence> newTrainList = new LinkedList<TemporalSentence>();
List<TemporalSentence> newTestList = new LinkedList<TemporalSentence>();
for (int j = 0; j < splitData.size(); j++){
if (i == j)
newTestList.addAll(splitData.get(i));
else
newTrainList.addAll(splitData.get(j));
}
// to make them into IDataCollection items:
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTest =
new TemporalSentenceDataset(newTestList);
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTrain =
new TemporalSentenceDataset(newTrainList);
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final TemporalTesterSmall tester = TemporalTesterSmall.build(newTest, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner =
new JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, newTrain, jParser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
OutputData outputData = new OutputData();
threads[i] = new TemporalThread(learner, tester, i, outputData, model);
threads[i].start();
outList[i] = outputData;
}
for (int i = 0; i < threads.length; i++){
try{
threads[i].join();
} catch (InterruptedException e){
e.printStackTrace();
System.err.println("Some problems getting the threads to join again!");
}
}
PrintStream out = new PrintStream(new File("output/totals.txt"));
OutputData averaged = OutputData.average(outList);
out.println(averaged);
out.close();
// Not crossval
} else {
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
final TemporalTesterSmall tester = TemporalTesterSmall.build(test, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner = new
JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, train, jParser);
learner.train(model);
// Within this tester, I should go through each example and use the
// visitor on each logical expression!
OutputData o = new OutputData();
tester.test(model, System.out,o);
}
//LOG.info("Total runtime %.4f seconds", Double.valueOf(System
// .currentTimeMillis() - startTime / 1000.0D));
}
| public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean readSerializedDatasets = false; // this takes precedence over booleans testingDataset, timebank, and crossVal.
boolean serializeDatasets = false;
boolean testingDataset = true; // testing dataset takes precidenence over timebank
// options for dataSetName: "tempeval3.aquaintAndTimebank.txt", "tempeval3.aquaint.txt", "tempeval3.timebank.txt"
String dataSetName = "tempeval3.aquaintAndTimebank.txt";
boolean crossVal = true;
int numIterations = 1;
Logger.DEFAULT_LOG = new Log(System.out);
Logger.setSkipPrefix(true);
LogLevel.INFO.set();
//long startTime = System.currentTimeMillis();
// Relative path for data directories
String datasetDir = "./data/dataset/";
String resourcesDir = "./data/resources/";
// Init the logical expression type system
// LogicLanguageServices.setInstance(new LogicLanguageServices(
// new TypeRepository(
// new File(resourcesDir + "tempeval.types.txt")), "i"));
LogicLanguageServices.setInstance(new LogicLanguageServices.Builder(
new TypeRepository(new File(resourcesDir + "tempeval.types.txt"))).setNumeralTypeName("i")
.setTypeComparator(new FlexibleTypeComparator()).build());
final ICategoryServices<LogicalExpression> categoryServices = new LogicalExpressionCategoryServices();
// Load the ontology
List<File> ontologyFiles = new LinkedList<File>();
ontologyFiles.add(new File(resourcesDir + "tempeval.predicates.txt"));
ontologyFiles.add(new File(resourcesDir + "tempeval.constants.txt"));
try {
// Ontology is currently not used, so we are just reading it, not
// storing
new Ontology(ontologyFiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
// When running on testing dataset, testingDataset = true
String dataLoc;
if (testingDataset)
dataLoc = "tempeval3.testing.txt";
else{
dataLoc = dataSetName;
}
//dataLoc = "tempeval.dataset.corrected.txt";
// these train and test should be of type
// IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, Pair<String, String>>>
TemporalSentenceDataset train = null;
TemporalSentenceDataset test = null;
// reading in the serialized datasets so we don't have to run the dependency parser again.
if (readSerializedDatasets){
train = TemporalSentenceDataset.readSerialized("data/serialized_data/trainingData.ser");
test = TemporalSentenceDataset.readSerialized("data/serialized_data/testingData.ser");
} else {
train = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
test = TemporalSentenceDataset
.read(new File(datasetDir + dataLoc),
new StubStringFilter(), true);
}
if (serializeDatasets){
System.out.print("Serializing the training data... ");
TemporalSentenceDataset.save("data/serialized_data/trainingData.ser", train);
System.out.println("Done!");
System.out.print("Serializing the testing data... ");
TemporalSentenceDataset.save("data/serialized_data/testingData.ser", test);
System.out.println("Done!");
}
LOG.info("Train Size: " + train.size());
LOG.info("Test Size: " + test.size());
// Below is the code from Geo880DevParameterEstimation. I am replacing this with code from Geo880Dev.
/*
// Init the lexicon
final ILexicon<LogicalExpression> lexicon = new Lexicon<LogicalExpression>();
lexicon.addEntriesFromFile(
new File(
resourcesDir + "tempeval.lexicon.txt"),
new StubStringFilter(), categoryServices,
EntryOrigin.FIXED_DOMAIN);
LOG.info("Size of lexicon: %d", lexicon.size());
LOG.info("Size of lexicon: %d", lexicon.size());
final LexicalFeatureSet<LogicalExpression> lexPhi = new LexicalFeatureSetBuilder<LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0))).build();
// Create the model
final Model<Sentence, LogicalExpression> model = new Model.Builder<Sentence, LogicalExpression>()
.addParseFeatureSet(
new LogicalExpressionCoordinationFeatureSet<Sentence>())
.addParseFeatureSet(
new LogicalExpressionTypeFeatureSet<Sentence>())
.addLexicalFeatureSet(lexPhi)
.setLexicon(new Lexicon<LogicalExpression>()).build();
*/
// Init the lexicon
// final Lexicon<LogicalExpression> fixed = new
// Lexicon<LogicalExpression>();
final ILexicon<LogicalExpression> fixedInput = new Lexicon<LogicalExpression>();
fixedInput.addEntriesFromFile(new File(resourcesDir
+ "tempeval.lexicon.txt"), new StubStringFilter(),
categoryServices, LexicalEntry.Origin.FIXED_DOMAIN);
final ILexicon<LogicalExpression> fixed = new Lexicon<LogicalExpression>();
// factor the fixed lexical entries
//for (final LexicalEntry<LogicalExpression> lex : fixedInput
// .toCollection()) {
// fixed.add(FactoredLexicon.factor(lex));
//}
//System.out.println(fixed);
// try two at factoring the fixed lexical entries:
for (final LexicalEntry<LogicalExpression> lex : fixedInput.toCollection()){
fixed.add(lex);
}
final LexicalFeatureSet<Sentence, LogicalExpression> lexPhi = new LexicalFeatureSet.Builder<Sentence,LogicalExpression>()
.setInitialFixedScorer(
new ExpLengthLexicalEntryScorer<LogicalExpression>(
10.0, 1.1))
.setInitialScorer(
new SkippingSensitiveLexicalEntryScorer<LogicalExpression>(
categoryServices,
-1.0,
new UniformScorer<LexicalEntry<LogicalExpression>>(
0.0)))
// .setInitialWeightScorer(gizaScores)
.build();
// Create the lexeme feature set
//final LexemeCooccurrenceScorer gizaScores;
// final DecoderHelper<LogicalExpression> decoderHelper = new
// DecoderHelper<LogicalExpression>(
// categoryServices);
//try {
// gizaScores = new LexemeCooccurrenceScorer(new File(resourcesDir
// + "/geo600.dev.giza_probs"));
//} catch (final IOException e) {
// System.err.println(e);
// throw new RuntimeException(e);
//}
//final LexemeFeatureSet lexemeFeats = new LexemeFeatureSet.Builder()
// .setInitialFixedScorer(new UniformScorer<Lexeme>(0.0))
// .setInitialScorer(new ScalingScorer<Lexeme>(10.0, gizaScores))
// .build();
// This was used for initializing the factored lexicon
final LexicalTemplateFeatureSet templateFeats = new LexicalTemplateFeatureSet.Builder()
.setScale(0.1)
// .setInitialWeightScorer(new LexicalSyntaxPenaltyScorer(-0.1))
.build();
// Create the entire feature collection
// Adjusted to move away from a factored lexicon
// Parsing rules
final RuleSetBuilder<LogicalExpression> ruleSetBuilder = new RuleSetBuilder<LogicalExpression>();
// Binary rules
ruleSetBuilder.add(new ForwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardComposition<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new ForwardApplication<LogicalExpression>(
categoryServices));
ruleSetBuilder.add(new BackwardApplication<LogicalExpression>(
categoryServices));
// Executor for multi-threading
final TinyExecutorService executor = new TinyExecutorService(Runtime
.getRuntime().availableProcessors());
LOG.info("Using %d threads", Runtime.getRuntime().availableProcessors());
final Set<Syntax> syntaxSet = new HashSet<Syntax>();
syntaxSet.add(Syntax.NP);
final SimpleFullParseFilter<LogicalExpression> parseFilter = new SimpleFullParseFilter<LogicalExpression>(
syntaxSet);
final AbstractCKYParser<LogicalExpression> parser = new CKYParser.Builder<LogicalExpression>(
categoryServices, parseFilter)//, executor)
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
ruleSetBuilder.build()))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new ForwardSkippingRule<LogicalExpression>(
categoryServices)))
.addBinaryParseRule(
new CKYBinaryParsingRule<LogicalExpression>(
new BackwardSkippingRule<LogicalExpression>(
categoryServices)))
.setMaxNumberOfCellsInSpan(100).build();
// Crossvalidation starts here.
if (crossVal){
double numberOfPartitions = 3.0;
// make a list
// use the constructor with TemporalSentenceDataset to make a new dataset.
System.out.println("Splitting the data...");
List<List<TemporalSentence>> splitData =
new LinkedList<List<TemporalSentence>>();
Iterator<TemporalSentence> iter = train.iterator();
int sentenceCount = 1;
List<TemporalSentence> tmp =
new LinkedList<TemporalSentence>();
while (iter.hasNext()){
tmp.add(iter.next());
// for testing:
if (sentenceCount % Math.round(train.size() / numberOfPartitions)== 0){
splitData.add(tmp);
tmp = new LinkedList<TemporalSentence>();
System.out.println();
System.out.println("sentenceCount: " + sentenceCount);
System.out.println("Train size: " + train.size());
System.out.println("size / " + numberOfPartitions + ": " + Math.round(train.size() / numberOfPartitions));
}
sentenceCount++;
}
System.out.println(" done.");
OutputData[] outList = new OutputData[splitData.size()];
// to make the threads
TemporalThread[] threads = new TemporalThread[splitData.size()];
for (int i = 0; i < splitData.size(); i++){
// to make the training and testing corpora
List<TemporalSentence> newTrainList = new LinkedList<TemporalSentence>();
List<TemporalSentence> newTestList = new LinkedList<TemporalSentence>();
for (int j = 0; j < splitData.size(); j++){
if (i == j)
newTestList.addAll(splitData.get(i));
else
newTrainList.addAll(splitData.get(j));
}
// to make them into IDataCollection items:
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTest =
new TemporalSentenceDataset(newTestList);
IDataCollection<? extends ILabeledDataItem<Pair<Sentence, String[]>, TemporalResult>> newTrain =
new TemporalSentenceDataset(newTrainList);
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final TemporalTesterSmall tester = TemporalTesterSmall.build(newTest, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner =
new JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, newTrain, jParser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
OutputData outputData = new OutputData();
threads[i] = new TemporalThread(learner, tester, i, outputData, model);
threads[i].start();
outList[i] = outputData;
}
for (int i = 0; i < threads.length; i++){
try{
threads[i].join();
} catch (InterruptedException e){
e.printStackTrace();
System.err.println("Some problems getting the threads to join again!");
}
}
PrintStream out = new PrintStream(new File("output/totals.txt"));
OutputData averaged = OutputData.average(outList);
out.println(averaged);
out.close();
// Not crossval
} else {
// Creating a joint parser.
final TemporalJointParser jParser = new TemporalJointParser(parser);
final JointModel<Sentence, String[], LogicalExpression, LogicalExpression> model
= new JointModel.Builder<Sentence, String[], LogicalExpression, LogicalExpression>()
//.addParseFeatureSet(
// new LogicalExpressionCoordinationFeatureSet<Sentence>(true, true, true))
//.addParseFeatureSet(
// new LogicalExpressionTypeFeatureSet<Sentence>())
.addJointFeatureSet(new TemporalContextFeatureSet())
.addJointFeatureSet(new TemporalReferenceFeatureSet())
.addJointFeatureSet(new TemporalTypeFeatureSet())
.addJointFeatureSet(new TemporalDayOfWeekFeatureSet())
.addLexicalFeatureSet(lexPhi)//.addLexicalFeatureSet(lexemeFeats)
//.addLexicalFeatureSet(templateFeats)
.setLexicon(new Lexicon<LogicalExpression>()).build();
// Initialize lexical features. This is not "natural" for every lexical
// feature set, only for this one, so it's done here and not on all
// lexical feature sets.
model.addFixedLexicalEntries(fixed.toCollection());
final TemporalTesterSmall tester = TemporalTesterSmall.build(test, jParser);
final ILearner<Sentence, LogicalExpression, JointModel<Sentence, String[], LogicalExpression, LogicalExpression>> learner = new
JointSimplePerceptron<Sentence, String[], LogicalExpression, LogicalExpression, TemporalResult>(
numIterations, train, jParser);
learner.train(model);
// Within this tester, I should go through each example and use the
// visitor on each logical expression!
OutputData o = new OutputData();
tester.test(model, System.out,o);
}
//LOG.info("Total runtime %.4f seconds", Double.valueOf(System
// .currentTimeMillis() - startTime / 1000.0D));
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
index 136f0478..fcd659b0 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
@@ -1,213 +1,213 @@
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2004 Klaus Bartz
*
* 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.izforge.izpack.panels;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPanelConstraints;
import com.izforge.izpack.gui.IzPanelLayout;
import com.izforge.izpack.gui.LayoutConstants;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.LayoutHelper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* This is a sub panel which contains a text field and a browse button for path selection. This is
* NOT an IzPanel, else it is made to use in an IzPanel for any path selection. If the IzPanel
* parent implements ActionListener, the ActionPerformed method will be called, if
* PathSelectionPanel.ActionPerformed was called with a source other than the browse button. This
* can be used to perform parentFrame.navigateNext in the IzPanel parent. An example implementation
* is done in com.izforge.izpack.panels.PathInputPanel.
*
* @author Klaus Bartz
* @author Jeff Gordon
*/
public class UserPathSelectionPanel extends JPanel implements ActionListener, LayoutConstants
{
/**
*
*/
private static final long serialVersionUID = 3618700794577105718L;
/**
* The text field for the path.
*/
private JTextField textField;
/**
* The 'browse' button.
*/
private JButton browseButton;
/**
* IzPanel parent (not the InstallerFrame).
*/
private IzPanel parent;
/**
* The installer internal data.
*/
private InstallData idata;
private String targetPanel;
private String variableName;
private String defaultPanelName = "TargetPanel";
/**
* The constructor. Be aware, parent is the parent IzPanel, not the installer frame.
*
* @param parent The parent IzPanel.
* @param idata The installer internal data.
*/
public UserPathSelectionPanel(IzPanel parent, InstallData idata, String targetPanel, String variableName)
{
super();
this.parent = parent;
this.idata = idata;
this.variableName = variableName;
this.targetPanel = targetPanel;
createLayout();
}
/**
* Creates the layout for this sub panel.
*/
protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
- textField = new JTextField(idata.getVariable(variableName));
+ textField = new JTextField(idata.getVariable(variableName), 10);
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
// There are problems with the size if no other component needs the
// full size. Sometimes directly, somtimes only after a back step.
public Dimension getMinimumSize()
{
Dimension ss = super.getPreferredSize();
Dimension retval = parent.getSize();
retval.height = ss.height;
return (retval);
}
/**
* Actions-handling method.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == browseButton)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
String path = fc.getSelectedFile().getAbsolutePath();
textField.setText(path);
}
}
else
{
if (parent instanceof ActionListener)
{
((ActionListener) parent).actionPerformed(e);
}
}
}
/**
* Returns the chosen path.
*
* @return the chosen path
*/
public String getPath()
{
return (textField.getText());
}
/**
* Sets the contents of the text field to the given path.
*
* @param path the path to be set
*/
public void setPath(String path)
{
textField.setText(path);
}
/**
* Returns the text input field for the path. This methode can be used to differ in a
* ActionPerformed method of the parent between the browse button and the text field.
*
* @return the text input field for the path
*/
public JTextField getPathInputField()
{
return textField;
}
/**
* Returns the browse button object for modification or for use with a different ActionListener.
*
* @return the browse button to open the JFileChooser
*/
public JButton getBrowseButton()
{
return browseButton;
}
}
| true | true | protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
textField = new JTextField(idata.getVariable(variableName));
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
| protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
textField = new JTextField(idata.getVariable(variableName), 10);
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
|
diff --git a/tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/master/querymaster/QueryUnitAttempt.java b/tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/master/querymaster/QueryUnitAttempt.java
index aac5e37e..8a68c264 100644
--- a/tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/master/querymaster/QueryUnitAttempt.java
+++ b/tajo-core/tajo-core-backend/src/main/java/org/apache/tajo/master/querymaster/QueryUnitAttempt.java
@@ -1,410 +1,413 @@
/**
* 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.tajo.master.querymaster;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.state.*;
import org.apache.tajo.QueryUnitAttemptId;
import org.apache.tajo.TajoProtos.TaskAttemptState;
import org.apache.tajo.catalog.statistics.TableStats;
import org.apache.tajo.ipc.TajoWorkerProtocol.TaskCompletionReport;
import org.apache.tajo.master.event.*;
import org.apache.tajo.master.event.QueryUnitAttemptScheduleEvent.QueryUnitAttemptScheduleContext;
import org.apache.tajo.master.event.TaskSchedulerEvent.EventType;
import org.apache.tajo.master.querymaster.QueryUnit.IntermediateEntry;
import org.apache.tajo.util.TajoIdUtils;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.apache.tajo.ipc.TajoWorkerProtocol.ShuffleFileOutput;
public class QueryUnitAttempt implements EventHandler<TaskAttemptEvent> {
private static final Log LOG = LogFactory.getLog(QueryUnitAttempt.class);
private final static int EXPIRE_TIME = 15000;
private final QueryUnitAttemptId id;
private final QueryUnit queryUnit;
final EventHandler eventHandler;
private ContainerId containerId;
private String hostName;
private int port;
private int expire;
private final Lock readLock;
private final Lock writeLock;
private final List<String> diagnostics = new ArrayList<String>();
private final QueryUnitAttemptScheduleContext scheduleContext;
protected static final StateMachineFactory
<QueryUnitAttempt, TaskAttemptState, TaskAttemptEventType, TaskAttemptEvent>
stateMachineFactory = new StateMachineFactory
<QueryUnitAttempt, TaskAttemptState, TaskAttemptEventType, TaskAttemptEvent>
(TaskAttemptState.TA_NEW)
// Transitions from TA_NEW state
.addTransition(TaskAttemptState.TA_NEW, TaskAttemptState.TA_UNASSIGNED,
TaskAttemptEventType.TA_SCHEDULE, new TaskAttemptScheduleTransition())
.addTransition(TaskAttemptState.TA_NEW, TaskAttemptState.TA_UNASSIGNED,
TaskAttemptEventType.TA_RESCHEDULE, new TaskAttemptScheduleTransition())
.addTransition(TaskAttemptState.TA_NEW, TaskAttemptState.TA_KILLED,
TaskAttemptEventType.TA_KILL,
new TaskKilledCompleteTransition())
// Transitions from TA_UNASSIGNED state
.addTransition(TaskAttemptState.TA_UNASSIGNED, TaskAttemptState.TA_ASSIGNED,
TaskAttemptEventType.TA_ASSIGNED,
new LaunchTransition())
.addTransition(TaskAttemptState.TA_UNASSIGNED, TaskAttemptState.TA_KILL_WAIT,
TaskAttemptEventType.TA_KILL,
new KillUnassignedTaskTransition())
// Transitions from TA_ASSIGNED state
.addTransition(TaskAttemptState.TA_ASSIGNED, TaskAttemptState.TA_ASSIGNED,
TaskAttemptEventType.TA_ASSIGNED, new AlreadyAssignedTransition())
.addTransition(TaskAttemptState.TA_ASSIGNED, TaskAttemptState.TA_KILL_WAIT,
TaskAttemptEventType.TA_KILL,
new KillTaskTransition())
.addTransition(TaskAttemptState.TA_ASSIGNED,
EnumSet.of(TaskAttemptState.TA_RUNNING, TaskAttemptState.TA_KILLED),
TaskAttemptEventType.TA_UPDATE, new StatusUpdateTransition())
.addTransition(TaskAttemptState.TA_ASSIGNED, TaskAttemptState.TA_SUCCEEDED,
TaskAttemptEventType.TA_DONE, new SucceededTransition())
.addTransition(TaskAttemptState.TA_ASSIGNED, TaskAttemptState.TA_FAILED,
TaskAttemptEventType.TA_FATAL_ERROR, new FailedTransition())
// Transitions from TA_RUNNING state
.addTransition(TaskAttemptState.TA_RUNNING,
EnumSet.of(TaskAttemptState.TA_RUNNING),
TaskAttemptEventType.TA_UPDATE, new StatusUpdateTransition())
.addTransition(TaskAttemptState.TA_RUNNING, TaskAttemptState.TA_KILL_WAIT,
TaskAttemptEventType.TA_KILL,
new KillTaskTransition())
.addTransition(TaskAttemptState.TA_RUNNING, TaskAttemptState.TA_SUCCEEDED,
TaskAttemptEventType.TA_DONE, new SucceededTransition())
.addTransition(TaskAttemptState.TA_RUNNING, TaskAttemptState.TA_FAILED,
TaskAttemptEventType.TA_FATAL_ERROR, new FailedTransition())
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_KILLED,
TaskAttemptEventType.TA_LOCAL_KILLED,
new TaskKilledCompleteTransition())
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_KILL_WAIT,
TaskAttemptEventType.TA_ASSIGNED,
new KillTaskTransition())
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_KILLED,
TaskAttemptEventType.TA_SCHEDULE_CANCELED,
new TaskKilledCompleteTransition())
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_KILLED,
TaskAttemptEventType.TA_DONE,
new TaskKilledCompleteTransition())
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_FAILED,
TaskAttemptEventType.TA_FATAL_ERROR)
.addTransition(TaskAttemptState.TA_KILL_WAIT, TaskAttemptState.TA_KILL_WAIT,
EnumSet.of(
TaskAttemptEventType.TA_KILL,
TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE,
TaskAttemptEventType.TA_UPDATE))
// Transitions from TA_SUCCEEDED state
.addTransition(TaskAttemptState.TA_SUCCEEDED, TaskAttemptState.TA_SUCCEEDED,
TaskAttemptEventType.TA_UPDATE)
.addTransition(TaskAttemptState.TA_SUCCEEDED, TaskAttemptState.TA_SUCCEEDED,
TaskAttemptEventType.TA_DONE, new AlreadyDoneTransition())
.addTransition(TaskAttemptState.TA_SUCCEEDED, TaskAttemptState.TA_FAILED,
TaskAttemptEventType.TA_FATAL_ERROR, new FailedTransition())
// Ignore-able transitions
.addTransition(TaskAttemptState.TA_SUCCEEDED, TaskAttemptState.TA_SUCCEEDED,
TaskAttemptEventType.TA_KILL)
// Transitions from TA_KILLED state
.addTransition(TaskAttemptState.TA_KILLED, TaskAttemptState.TA_KILLED,
TaskAttemptEventType.TA_DIAGNOSTICS_UPDATE)
// Ignore-able transitions
.addTransition(TaskAttemptState.TA_KILLED, TaskAttemptState.TA_KILLED,
EnumSet.of(
TaskAttemptEventType.TA_UPDATE))
.installTopology();
private final StateMachine<TaskAttemptState, TaskAttemptEventType, TaskAttemptEvent>
stateMachine;
public QueryUnitAttempt(final QueryUnitAttemptScheduleContext scheduleContext,
final QueryUnitAttemptId id, final QueryUnit queryUnit,
final EventHandler eventHandler) {
this.scheduleContext = scheduleContext;
this.id = id;
this.expire = QueryUnitAttempt.EXPIRE_TIME;
this.queryUnit = queryUnit;
this.eventHandler = eventHandler;
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
this.readLock = readWriteLock.readLock();
this.writeLock = readWriteLock.writeLock();
stateMachine = stateMachineFactory.make(this);
}
public TaskAttemptState getState() {
readLock.lock();
try {
return stateMachine.getCurrentState();
} finally {
readLock.unlock();
}
}
public QueryUnitAttemptId getId() {
return this.id;
}
public boolean isLeafTask() {
return this.queryUnit.isLeafTask();
}
public QueryUnit getQueryUnit() {
return this.queryUnit;
}
public String getHost() {
return this.hostName;
}
public int getPort() {
return this.port;
}
public void setContainerId(ContainerId containerId) {
this.containerId = containerId;
}
public void setHost(String host) {
this.hostName = host;
}
public void setPullServerPort(int port) {
this.port = port;
}
public int getPullServerPort() {
return port;
}
public synchronized void setExpireTime(int expire) {
this.expire = expire;
}
public synchronized void updateExpireTime(int period) {
this.setExpireTime(this.expire - period);
}
public synchronized void resetExpireTime() {
this.setExpireTime(QueryUnitAttempt.EXPIRE_TIME);
}
public int getLeftTime() {
return this.expire;
}
private void fillTaskStatistics(TaskCompletionReport report) {
if (report.getShuffleFileOutputsCount() > 0) {
this.getQueryUnit().setShuffleFileOutputs(report.getShuffleFileOutputsList());
List<IntermediateEntry> partitions = new ArrayList<IntermediateEntry>();
for (ShuffleFileOutput p : report.getShuffleFileOutputsList()) {
IntermediateEntry entry = new IntermediateEntry(getId().getQueryUnitId().getId(),
getId().getId(), p.getPartId(), getHost(), getPullServerPort());
partitions.add(entry);
}
this.getQueryUnit().setIntermediateData(partitions);
}
if (report.hasResultStats()) {
this.getQueryUnit().setStats(new TableStats(report.getResultStats()));
}
}
private static class TaskAttemptScheduleTransition implements
SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt, TaskAttemptEvent taskAttemptEvent) {
taskAttempt.eventHandler.handle(new QueryUnitAttemptScheduleEvent(
EventType.T_SCHEDULE, taskAttempt.getQueryUnit().getId().getExecutionBlockId(),
taskAttempt.scheduleContext, taskAttempt));
}
}
private static class KillUnassignedTaskTransition implements
SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt, TaskAttemptEvent taskAttemptEvent) {
taskAttempt.eventHandler.handle(new QueryUnitAttemptScheduleEvent(
EventType.T_SCHEDULE_CANCEL, taskAttempt.getQueryUnit().getId().getExecutionBlockId(),
taskAttempt.scheduleContext, taskAttempt));
}
}
private static class LaunchTransition
implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt,
TaskAttemptEvent event) {
TaskAttemptAssignedEvent castEvent = (TaskAttemptAssignedEvent) event;
taskAttempt.containerId = castEvent.getContainerId();
taskAttempt.setHost(castEvent.getHostName());
taskAttempt.setPullServerPort(castEvent.getPullServerPort());
taskAttempt.eventHandler.handle(
new TaskTAttemptEvent(taskAttempt.getId(),
TaskEventType.T_ATTEMPT_LAUNCHED));
}
}
private static class TaskKilledCompleteTransition implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt,
TaskAttemptEvent event) {
taskAttempt.getQueryUnit().handle(new TaskEvent(taskAttempt.getId().getQueryUnitId(),
TaskEventType.T_ATTEMPT_KILLED));
LOG.info(taskAttempt.getId() + " Received TA_KILLED Status from LocalTask");
}
}
private static class StatusUpdateTransition
implements MultipleArcTransition<QueryUnitAttempt, TaskAttemptEvent, TaskAttemptState> {
@Override
public TaskAttemptState transition(QueryUnitAttempt taskAttempt,
TaskAttemptEvent event) {
TaskAttemptStatusUpdateEvent updateEvent = (TaskAttemptStatusUpdateEvent) event;
switch (updateEvent.getStatus().getState()) {
case TA_PENDING:
case TA_RUNNING:
return TaskAttemptState.TA_RUNNING;
default:
return taskAttempt.getState();
}
}
}
private void addDiagnosticInfo(String diag) {
if (diag != null && !diag.equals("")) {
diagnostics.add(diag);
}
}
private static class AlreadyAssignedTransition
implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent>{
@Override
public void transition(QueryUnitAttempt queryUnitAttempt,
TaskAttemptEvent taskAttemptEvent) {
}
}
private static class AlreadyDoneTransition
implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent>{
@Override
public void transition(QueryUnitAttempt queryUnitAttempt,
TaskAttemptEvent taskAttemptEvent) {
}
}
private static class SucceededTransition implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt,
TaskAttemptEvent event) {
TaskCompletionReport report = ((TaskCompletionEvent)event).getReport();
try {
taskAttempt.fillTaskStatistics(report);
taskAttempt.eventHandler.handle(new TaskTAttemptEvent(taskAttempt.getId(), TaskEventType.T_ATTEMPT_SUCCEEDED));
} catch (Throwable t) {
taskAttempt.eventHandler.handle(new TaskFatalErrorEvent(taskAttempt.getId(), t.getMessage()));
}
}
}
private static class KillTaskTransition implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent> {
@Override
public void transition(QueryUnitAttempt taskAttempt, TaskAttemptEvent event) {
taskAttempt.eventHandler.handle(new LocalTaskEvent(taskAttempt.getId(), taskAttempt.containerId,
LocalTaskEventType.KILL));
}
}
private static class FailedTransition implements SingleArcTransition<QueryUnitAttempt, TaskAttemptEvent>{
@Override
public void transition(QueryUnitAttempt taskAttempt, TaskAttemptEvent event) {
TaskFatalErrorEvent errorEvent = (TaskFatalErrorEvent) event;
taskAttempt.eventHandler.handle(new TaskTAttemptEvent(taskAttempt.getId(), TaskEventType.T_ATTEMPT_FAILED));
taskAttempt.addDiagnosticInfo(errorEvent.errorMessage());
LOG.error("FROM " + taskAttempt.getHost() + " >> " + errorEvent.errorMessage());
}
}
@Override
public void handle(TaskAttemptEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing " + event.getTaskAttemptId() + " of type " + event.getType());
}
try {
writeLock.lock();
TaskAttemptState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitonException e) {
- LOG.error("Can't handle this event at current state of "
- + event.getTaskAttemptId() + ")", e);
- eventHandler.handle(new QueryEvent(TajoIdUtils.parseQueryId(getId().toString()),
- QueryEventType.INTERNAL_ERROR));
+ LOG.error("Can't handle this event at current state of " + event.getTaskAttemptId() + ")", e);
+ eventHandler.handle(
+ new SubQueryDiagnosticsUpdateEvent(event.getTaskAttemptId().getQueryUnitId().getExecutionBlockId(),
+ "Can't handle this event at current state of " + event.getTaskAttemptId() + ")"));
+ eventHandler.handle(
+ new SubQueryEvent(event.getTaskAttemptId().getQueryUnitId().getExecutionBlockId(),
+ SubQueryEventType.SQ_INTERNAL_ERROR));
}
//notify the eventhandler of state change
if (LOG.isDebugEnabled()) {
if (oldState != getState()) {
LOG.debug(id + " TaskAttempt Transitioned from " + oldState + " to "
+ getState());
}
}
}
finally {
writeLock.unlock();
}
}
}
| true | true | public void handle(TaskAttemptEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing " + event.getTaskAttemptId() + " of type " + event.getType());
}
try {
writeLock.lock();
TaskAttemptState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitonException e) {
LOG.error("Can't handle this event at current state of "
+ event.getTaskAttemptId() + ")", e);
eventHandler.handle(new QueryEvent(TajoIdUtils.parseQueryId(getId().toString()),
QueryEventType.INTERNAL_ERROR));
}
//notify the eventhandler of state change
if (LOG.isDebugEnabled()) {
if (oldState != getState()) {
LOG.debug(id + " TaskAttempt Transitioned from " + oldState + " to "
+ getState());
}
}
}
finally {
writeLock.unlock();
}
}
| public void handle(TaskAttemptEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing " + event.getTaskAttemptId() + " of type " + event.getType());
}
try {
writeLock.lock();
TaskAttemptState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitonException e) {
LOG.error("Can't handle this event at current state of " + event.getTaskAttemptId() + ")", e);
eventHandler.handle(
new SubQueryDiagnosticsUpdateEvent(event.getTaskAttemptId().getQueryUnitId().getExecutionBlockId(),
"Can't handle this event at current state of " + event.getTaskAttemptId() + ")"));
eventHandler.handle(
new SubQueryEvent(event.getTaskAttemptId().getQueryUnitId().getExecutionBlockId(),
SubQueryEventType.SQ_INTERNAL_ERROR));
}
//notify the eventhandler of state change
if (LOG.isDebugEnabled()) {
if (oldState != getState()) {
LOG.debug(id + " TaskAttempt Transitioned from " + oldState + " to "
+ getState());
}
}
}
finally {
writeLock.unlock();
}
}
|
diff --git a/LaTeXDraw/src/net/sf/latexdraw/instruments/MagneticGridCustomiser.java b/LaTeXDraw/src/net/sf/latexdraw/instruments/MagneticGridCustomiser.java
index e5e4c33d..d8a98b75 100644
--- a/LaTeXDraw/src/net/sf/latexdraw/instruments/MagneticGridCustomiser.java
+++ b/LaTeXDraw/src/net/sf/latexdraw/instruments/MagneticGridCustomiser.java
@@ -1,277 +1,277 @@
package net.sf.latexdraw.instruments;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import net.sf.latexdraw.actions.ModifyMagneticGrid;
import net.sf.latexdraw.actions.ModifyMagneticGrid.GridProperties;
import net.sf.latexdraw.badaboom.BadaboomCollector;
import net.sf.latexdraw.glib.ui.LMagneticGrid;
import net.sf.latexdraw.glib.ui.LMagneticGrid.GridStyle;
import net.sf.latexdraw.lang.LangTool;
import net.sf.latexdraw.util.LResources;
import org.malai.instrument.Link;
import org.malai.instrument.WidgetInstrument;
import org.malai.interaction.library.CheckBoxModified;
import org.malai.interaction.library.ListSelectionModified;
import org.malai.interaction.library.SpinnerModified;
import org.malai.ui.UIComposer;
import org.malai.undo.Undoable;
import org.malai.widget.MCheckBox;
import org.malai.widget.MComboBox;
import org.malai.widget.MSpinner;
/**
* This instrument customises the magnetic grid.<br>
* <br>
* This file is part of LaTeXDraw<br>
* Copyright (c) 2005-2012 Arnaud BLOUIN<br>
* <br>
* LaTeXDraw 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.<br>
* <br>
* LaTeXDraw is distributed 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.<br>
* <br>
* 11/14/10<br>
* @author Arnaud BLOUIN
* @version 3.0
*/
public class MagneticGridCustomiser extends WidgetInstrument {
/** The grid to customise. */
protected LMagneticGrid grid;
/** Contains the different possible kind of grids. */
protected MComboBox styleList;
/** Sets if the grid is magnetic. */
protected MCheckBox magneticCB;
/** Defines the spacing of the personal grid. */
protected MSpinner gridSpacing;
/**
* Initialises the instrument.
* @param composer The composer that manages the widgets of the instrument.
* @param grid The grid to customise.
* @throws IllegalArgumentException If the given grid is null.
* @since 3.0
*/
public MagneticGridCustomiser(final UIComposer<?> composer, final LMagneticGrid grid) {
super(composer);
if(grid==null)
throw new IllegalArgumentException();
this.grid = grid;
initialiseWidgets();
}
@Override
protected void initialiseWidgets() {
styleList = createStyleList();
SpinnerNumberModel model= new SpinnerNumberModel(10, 2, 100000, 1);
gridSpacing = new MSpinner(model, new JLabel(LResources.GRID_GAP_ICON));
gridSpacing.setEditor(new JSpinner.NumberEditor(gridSpacing, "0"));//$NON-NLS-1$
gridSpacing.setToolTipText(LangTool.INSTANCE.getString18("LaTeXDrawFrame.15")); //$NON-NLS-1$
magneticCB = new MCheckBox(LangTool.INSTANCE.getString18("LaTeXDrawFrame.13")); //$NON-NLS-1$
magneticCB.setToolTipText(LangTool.INSTANCE.getString18("LaTeXDrawFrame.14")); //$NON-NLS-1$
}
/**
* @return The list widget that contains the different style of the magnetic grid.
* @since 3.0
*/
public static MComboBox createStyleList() {
final MComboBox list = new MComboBox();
list.addItem(GridStyle.STANDARD.getLabel());
list.addItem(GridStyle.CUSTOMISED.getLabel());
list.addItem(GridStyle.NONE.getLabel());
return list;
}
@Override
public void onUndoableUndo(final Undoable undoable) {
super.onUndoableUndo(undoable);
update();
}
@Override
public void onUndoableRedo(final Undoable undoable) {
super.onUndoableRedo(undoable);
update();
}
@Override
public void interimFeedback() {
super.interimFeedback();
update();
}
protected void update() {
final GridStyle style = grid.getStyle();
final boolean visible = style!=GridStyle.NONE;
- gridSpacing.setVisible(visible && style==GridStyle.CUSTOMISED);
- magneticCB.setVisible(visible);
+ composer.setWidgetVisible(gridSpacing, visible && style==GridStyle.CUSTOMISED);
+ composer.setWidgetVisible(magneticCB, visible);
styleList.setSelectedItemSafely(style.getLabel());
if(visible) {
if(style==GridStyle.CUSTOMISED)
gridSpacing.setValueSafely(grid.getGridSpacing());
magneticCB.setSelected(grid.isMagnetic());
}
}
@Override
protected void initialiseLinks() {
try{
addLink(new List2ChangeStyle(this));
addLink(new Spinner2GridSpacing(this));
addLink(new CheckBox2MagneticGrid(this));
}catch(InstantiationException e){
BadaboomCollector.INSTANCE.add(e);
}catch(IllegalAccessException e){
BadaboomCollector.INSTANCE.add(e);
}
}
@Override
public void setActivated(final boolean activated) {
super.setActivated(activated);
composer.setWidgetVisible(gridSpacing, activated);
composer.setWidgetVisible(magneticCB, activated);
composer.setWidgetVisible(styleList, activated);
}
/**
* @return The list that contains the different possible kind of grids.
* @since 3.0
*/
public MComboBox getStyleList() {
return styleList;
}
/**
* @return The check box that sets if the grid is magnetic.
* @since 3.0
*/
public MCheckBox getMagneticCB() {
return magneticCB;
}
/**
* @return The spinner that defines the spacing of the personal grid.
* @since 3.0
*/
public MSpinner getGridSpacing() {
return gridSpacing;
}
}
/**
* Links a check-box widget to an action that sets if the grid is magnetic.
*/
class CheckBox2MagneticGrid extends Link<ModifyMagneticGrid, CheckBoxModified, MagneticGridCustomiser> {
/**
* Initialises the link.
* @since 3.0
*/
protected CheckBox2MagneticGrid(final MagneticGridCustomiser ins) throws InstantiationException, IllegalAccessException {
super(ins, false, ModifyMagneticGrid.class, CheckBoxModified.class);
}
@Override
public void initAction() {
action.setProperty(GridProperties.MAGNETIC);
action.setGrid(instrument.grid);
action.setValue(interaction.getCheckBox().isSelected());
}
@Override
public boolean isConditionRespected() {
return interaction.getCheckBox()==instrument.magneticCB;
}
}
/**
* Links a spinner widget to an action that modifies the spacing of the customised magnetic grid.
*/
class Spinner2GridSpacing extends Link<ModifyMagneticGrid, SpinnerModified, MagneticGridCustomiser> {
/**
* Initialises the link.
* @since 3.0
*/
protected Spinner2GridSpacing(final MagneticGridCustomiser ins) throws InstantiationException, IllegalAccessException {
super(ins, false, ModifyMagneticGrid.class, SpinnerModified.class);
}
@Override
public void initAction() {
action.setProperty(GridProperties.GRID_SPACING);
action.setGrid(instrument.grid);
}
@Override
public void updateAction() {
action.setValue(Integer.valueOf(interaction.getSpinner().getValue().toString()));
}
@Override
public boolean isConditionRespected() {
return interaction.getSpinner()==instrument.gridSpacing;
}
}
/**
* Links a list widget to an action that modifies the style of the magnetic grid.
*/
class List2ChangeStyle extends Link<ModifyMagneticGrid, ListSelectionModified, MagneticGridCustomiser> {
/**
* Initialises the link.
* @since 3.0
*/
protected List2ChangeStyle(final MagneticGridCustomiser ins) throws InstantiationException, IllegalAccessException {
super(ins, false, ModifyMagneticGrid.class, ListSelectionModified.class);
}
@Override
public void initAction() {
action.setValue(GridStyle.getStyleFromLabel(interaction.getList().getSelectedObjects()[0].toString()));
action.setGrid(instrument.grid);
action.setProperty(GridProperties.STYLE);
}
@Override
public boolean isConditionRespected() {
return interaction.getList()==instrument.styleList;
}
}
| true | true | protected void update() {
final GridStyle style = grid.getStyle();
final boolean visible = style!=GridStyle.NONE;
gridSpacing.setVisible(visible && style==GridStyle.CUSTOMISED);
magneticCB.setVisible(visible);
styleList.setSelectedItemSafely(style.getLabel());
if(visible) {
if(style==GridStyle.CUSTOMISED)
gridSpacing.setValueSafely(grid.getGridSpacing());
magneticCB.setSelected(grid.isMagnetic());
}
}
| protected void update() {
final GridStyle style = grid.getStyle();
final boolean visible = style!=GridStyle.NONE;
composer.setWidgetVisible(gridSpacing, visible && style==GridStyle.CUSTOMISED);
composer.setWidgetVisible(magneticCB, visible);
styleList.setSelectedItemSafely(style.getLabel());
if(visible) {
if(style==GridStyle.CUSTOMISED)
gridSpacing.setValueSafely(grid.getGridSpacing());
magneticCB.setSelected(grid.isMagnetic());
}
}
|
diff --git a/src/btwmods/util/Zones.java b/src/btwmods/util/Zones.java
index b8699e9..9b31b14 100644
--- a/src/btwmods/util/Zones.java
+++ b/src/btwmods/util/Zones.java
@@ -1,114 +1,114 @@
package btwmods.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.src.ChunkCoordIntPair;
import btwmods.util.intervals.IntervalTree;
public class Zones<Type> {
private boolean hasAreas = false;
private Set<Area<Type>> areas = new HashSet<Area<Type>>();
private Map<ChunkCoordIntPair, IntervalTree<Area<Type>>> intervalsByRegion = new HashMap<ChunkCoordIntPair, IntervalTree<Area<Type>>>();
public boolean add(Area<Type> area) {
boolean added = areas.add(area);
if (added) {
// Add the area to it's respective regions.
for (int regionX = area.x1 >> 9; regionX <= area.x2 >> 9; regionX++) {
for (int regionZ = area.z1 >> 9; regionZ <= area.z2 >> 9; regionZ++) {
ChunkCoordIntPair coords = new ChunkCoordIntPair(regionX, regionZ);
IntervalTree<Area<Type>> intervals = intervalsByRegion.get(coords);
if (intervals == null)
intervalsByRegion.put(coords, intervals = new IntervalTree<Area<Type>>());
intervals.addInterval(area.x1 - 1, area.x2 + 1, area);
}
}
}
// TODO: clear any cache.
hasAreas = true;
return added;
}
public boolean remove(Area<Type> area) {
boolean removed = areas.remove(area);
if (removed) {
for (int regionX = area.x1 >> 9; regionX <= area.x2 >> 9; regionX++) {
for (int regionZ = area.z1 >> 9; regionZ <= area.z2 >> 9; regionZ++) {
ChunkCoordIntPair coords = new ChunkCoordIntPair(regionX, regionZ);
IntervalTree<Area<Type>> intervals = intervalsByRegion.get(coords);
if (intervals != null)
intervals.removeByData(area);
if (intervals.listSize() == 0)
intervalsByRegion.remove(coords);
}
}
}
hasAreas = areas.size() > 0;
// TODO: clear any cache.
return removed;
}
public List<Area<Type>> get(int x, int z) {
return get(x, 0, z, false);
}
public List<Area<Type>> get(int x, int y, int z) {
return get(x, y, z, true);
}
private List<Area<Type>> get(int x, int y, int z, boolean checkY) {
ArrayList<Area<Type>> areas = new ArrayList<Area<Type>>();
if (hasAreas) {
// Get areas for the region the X and Z are in.
IntervalTree tree = intervalsByRegion.get(new ChunkCoordIntPair(x >> 9, z >> 9));
if (tree != null) {
List<Area<Type>> intervalAreas = tree.get(x);
int size = intervalAreas.size();
// Check all the areas that matched X.
for (int i = 0; i < size; i++) {
- Area<Type> area = intervalAreas.get(0);
+ Area<Type> area = intervalAreas.get(i);
// Check if the Z matches.
if (z >= area.z1 && z <= area.z2) {
// Also check the Y if is a cube and checking Y
if (checkY && area instanceof Cube) {
Cube cube = (Cube)area;
if (y >= cube.y1 && y <= cube.y2) {
areas.add(area);
}
}
else {
areas.add(area);
}
}
}
}
}
return areas;
}
}
| true | true | private List<Area<Type>> get(int x, int y, int z, boolean checkY) {
ArrayList<Area<Type>> areas = new ArrayList<Area<Type>>();
if (hasAreas) {
// Get areas for the region the X and Z are in.
IntervalTree tree = intervalsByRegion.get(new ChunkCoordIntPair(x >> 9, z >> 9));
if (tree != null) {
List<Area<Type>> intervalAreas = tree.get(x);
int size = intervalAreas.size();
// Check all the areas that matched X.
for (int i = 0; i < size; i++) {
Area<Type> area = intervalAreas.get(0);
// Check if the Z matches.
if (z >= area.z1 && z <= area.z2) {
// Also check the Y if is a cube and checking Y
if (checkY && area instanceof Cube) {
Cube cube = (Cube)area;
if (y >= cube.y1 && y <= cube.y2) {
areas.add(area);
}
}
else {
areas.add(area);
}
}
}
}
}
return areas;
}
| private List<Area<Type>> get(int x, int y, int z, boolean checkY) {
ArrayList<Area<Type>> areas = new ArrayList<Area<Type>>();
if (hasAreas) {
// Get areas for the region the X and Z are in.
IntervalTree tree = intervalsByRegion.get(new ChunkCoordIntPair(x >> 9, z >> 9));
if (tree != null) {
List<Area<Type>> intervalAreas = tree.get(x);
int size = intervalAreas.size();
// Check all the areas that matched X.
for (int i = 0; i < size; i++) {
Area<Type> area = intervalAreas.get(i);
// Check if the Z matches.
if (z >= area.z1 && z <= area.z2) {
// Also check the Y if is a cube and checking Y
if (checkY && area instanceof Cube) {
Cube cube = (Cube)area;
if (y >= cube.y1 && y <= cube.y2) {
areas.add(area);
}
}
else {
areas.add(area);
}
}
}
}
}
return areas;
}
|
diff --git a/src/main/java/be/Balor/Manager/Commands/Player/Search.java b/src/main/java/be/Balor/Manager/Commands/Player/Search.java
index 4fc0fde5..26490ce1 100644
--- a/src/main/java/be/Balor/Manager/Commands/Player/Search.java
+++ b/src/main/java/be/Balor/Manager/Commands/Player/Search.java
@@ -1,97 +1,97 @@
/*************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd 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.
*
* AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.
*
**************************************************************************/
package be.Balor.Manager.Commands.Player;
import java.net.InetAddress;
import java.util.List;
import java.util.TreeSet;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import be.Balor.Manager.Commands.CommandArgs;
import be.Balor.Manager.Exceptions.PlayerNotFound;
import be.Balor.Manager.Permissions.ActionNotPermitedException;
import be.Balor.Player.ACPlayer;
import be.Balor.Player.PlayerManager;
import be.Balor.Tools.Utils;
import be.Balor.bukkit.AdminCmd.ACPluginManager;
import com.google.common.base.Joiner;
/**
* @author Lathanael (aka Philippe Leipold)
*
*/
public class Search extends PlayerCommand {
public Search() {
cmdName = "bal_search";
permNode = "admincmd.player.search";
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.Commands.CoreCommand#execute(org.bukkit.command.
* CommandSender, be.Balor.Manager.Commands.CommandArgs)
*/
@Override
public void execute(final CommandSender sender, final CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
if (args.hasFlag('i')) {
final String ip = args.getValueFlag('i');
if (ip == null || ip.equals("") || ip.length() == 0) {
return;
}
final Player[] onPlayers = ACPluginManager.getServer().getOnlinePlayers();
final List<ACPlayer> exPlayers = PlayerManager.getInstance().getExistingPlayers();
final TreeSet<String> players = new TreeSet<String>();
final TreeSet<String> playersOld = new TreeSet<String>();
final String on = "[ON] ", off = "[OFF] ";
InetAddress ipAdress;
for (final Player p : onPlayers) {
ipAdress = p.getAddress().getAddress();
- if (ipAdress != null && ipAdress.toString().equals(ip)) {
+ if (ipAdress != null && ipAdress.toString().substring(1).equals(ip)) {
players.add(on + Utils.getPlayerName(p));
playersOld.add(p.getName());
}
}
String ip2;
for (final ACPlayer p : exPlayers) {
ip2 = p.getInformation("last-ip").getString();
- if (ip2 != null && ip2.toString().equals(ip) && !playersOld.contains(p.getName())) {
+ if (ip2 != null && ip2.contains(ip) && !playersOld.contains(p.getName())) {
players.add(off + p.getName());
}
}
final String found = Joiner.on(", ").join(players);
sender.sendMessage(found);
return;
}
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.Commands.CoreCommand#argsCheck(java.lang.String[])
*/
@Override
public boolean argsCheck(final String... args) {
return args != null && args.length >= 1;
}
}
| false | true | public void execute(final CommandSender sender, final CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
if (args.hasFlag('i')) {
final String ip = args.getValueFlag('i');
if (ip == null || ip.equals("") || ip.length() == 0) {
return;
}
final Player[] onPlayers = ACPluginManager.getServer().getOnlinePlayers();
final List<ACPlayer> exPlayers = PlayerManager.getInstance().getExistingPlayers();
final TreeSet<String> players = new TreeSet<String>();
final TreeSet<String> playersOld = new TreeSet<String>();
final String on = "[ON] ", off = "[OFF] ";
InetAddress ipAdress;
for (final Player p : onPlayers) {
ipAdress = p.getAddress().getAddress();
if (ipAdress != null && ipAdress.toString().equals(ip)) {
players.add(on + Utils.getPlayerName(p));
playersOld.add(p.getName());
}
}
String ip2;
for (final ACPlayer p : exPlayers) {
ip2 = p.getInformation("last-ip").getString();
if (ip2 != null && ip2.toString().equals(ip) && !playersOld.contains(p.getName())) {
players.add(off + p.getName());
}
}
final String found = Joiner.on(", ").join(players);
sender.sendMessage(found);
return;
}
}
| public void execute(final CommandSender sender, final CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
if (args.hasFlag('i')) {
final String ip = args.getValueFlag('i');
if (ip == null || ip.equals("") || ip.length() == 0) {
return;
}
final Player[] onPlayers = ACPluginManager.getServer().getOnlinePlayers();
final List<ACPlayer> exPlayers = PlayerManager.getInstance().getExistingPlayers();
final TreeSet<String> players = new TreeSet<String>();
final TreeSet<String> playersOld = new TreeSet<String>();
final String on = "[ON] ", off = "[OFF] ";
InetAddress ipAdress;
for (final Player p : onPlayers) {
ipAdress = p.getAddress().getAddress();
if (ipAdress != null && ipAdress.toString().substring(1).equals(ip)) {
players.add(on + Utils.getPlayerName(p));
playersOld.add(p.getName());
}
}
String ip2;
for (final ACPlayer p : exPlayers) {
ip2 = p.getInformation("last-ip").getString();
if (ip2 != null && ip2.contains(ip) && !playersOld.contains(p.getName())) {
players.add(off + p.getName());
}
}
final String found = Joiner.on(", ").join(players);
sender.sendMessage(found);
return;
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/preferences/PreferenceInitializer.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/preferences/PreferenceInitializer.java
index cd87e167c..78baa0ccf 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/preferences/PreferenceInitializer.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/preferences/PreferenceInitializer.java
@@ -1,202 +1,204 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.preferences;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jface.preference.IPreferenceStore;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.feedback.AbstractFeedbackManager;
import de.fu_berlin.inf.dpp.feedback.FeedbackManager;
import de.fu_berlin.inf.dpp.videosharing.VideoSharing;
import de.fu_berlin.inf.dpp.videosharing.preferences.VideoSharingPreferenceHelper;
import de.fu_berlin.inf.dpp.videosharing.source.Screen;
/**
* Class used to initialize default preference values.
*
* @author rdjemili
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer
*/
protected static Logger log = Logger.getLogger(PreferenceInitializer.class
.getName());
@Override
public void initializeDefaultPreferences() {
IEclipsePreferences prefs = new DefaultScope().getNode(Saros.SAROS);
setPreferences(prefs);
}
public static void setPreferences(IEclipsePreferences prefs) {
setPreferences(new IEclipsePreferencesWrapper(prefs));
}
public static void setPreferences(IPreferenceStore preferenceStore) {
setPreferences(new IPreferenceStoreWrapper(preferenceStore));
}
private static void setPreferences(PreferenceHolderWrapper prefs) {
prefs.setValue(PreferenceConstants.GETTING_STARTED_FINISHED, false);
prefs.setValue(PreferenceConstants.ENCRYPT_ACCOUNT, false);
prefs.setValue(PreferenceConstants.AUTO_CONNECT, true);
prefs.setValue(PreferenceConstants.AUTO_PORTMAPPING_DEVICEID, "");
prefs.setValue(PreferenceConstants.GATEWAYCHECKPERFORMED, false);
prefs.setValue(PreferenceConstants.AUTO_FOLLOW_MODE, false);
prefs.setValue(PreferenceConstants.NEEDS_BASED_SYNC, "undefined");
prefs.setValue(PreferenceConstants.SKYPE_USERNAME, "");
prefs.setValue(PreferenceConstants.DEBUG, false);
prefs.setValue(PreferenceConstants.FILE_TRANSFER_PORT, 7777);
prefs.setValue(PreferenceConstants.USE_NEXT_PORTS_FOR_FILE_TRANSFER,
true);
prefs.setValue(PreferenceConstants.LOCAL_SOCKS5_PROXY_DISABLED, false);
prefs.setValue(PreferenceConstants.FORCE_FILETRANSFER_BY_CHAT, false);
prefs.setValue(PreferenceConstants.STUN, "stunserver.org");
prefs.setValue(PreferenceConstants.STUN_PORT, 3478);
prefs.setValue(PreferenceConstants.MILLIS_UPDATE, 300);
prefs.setValue(PreferenceConstants.AUTO_ACCEPT_INVITATION, false);
prefs.setValue(PreferenceConstants.CONCURRENT_UNDO, false);
prefs.setValue(PreferenceConstants.PING_PONG, false);
prefs.setValue(PreferenceConstants.DISABLE_VERSION_CONTROL, false);
// XMPP
prefs.setValue(PreferenceConstants.DEFAULT_XMPP_PORT, 5222);
// InvitationDialog
prefs.setValue(PreferenceConstants.AUTO_CLOSE_DIALOG, true);
prefs.setValue(PreferenceConstants.SKIP_SYNC_SELECTABLE, false);
+ prefs.setValue(
+ PreferenceConstants.BUDDYSELECTION_FILTERNONSAROSBUDDIES, true);
// its a new workspace per default, is set to false after first start in
// earlyStartup()
prefs.setValue(PreferenceConstants.NEW_WORKSPACE, true);
// Initialize Feedback Preferences
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_DISABLED,
FeedbackManager.FEEDBACK_ENABLED);
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_INTERVAL, 5);
prefs.setValue(PreferenceConstants.STATISTIC_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION_FULL,
AbstractFeedbackManager.FORBID);
// Communication default settings
prefs.setValue(PreferenceConstants.CHATSERVER,
"conference.jabber.ccc.de");
prefs.setValue(PreferenceConstants.USE_DEFAULT_CHATSERVER, true);
prefs.setValue(PreferenceConstants.BEEP_UPON_IM, true);
prefs.setValue(PreferenceConstants.AUDIO_VBR, true);
prefs.setValue(PreferenceConstants.AUDIO_ENABLE_DTX, true);
prefs.setValue(PreferenceConstants.AUDIO_SAMPLERATE, "44100");
prefs.setValue(PreferenceConstants.AUDIO_QUALITY_LEVEL, "8");
// videosharing
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_FRAMERATE, 5);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_RESOLUTION,
VideoSharingPreferenceHelper.RESOLUTIONS[2][1]);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_WIDTH, 320);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_HEIGHT, 240);
prefs.setValue(PreferenceConstants.ENCODING_MAX_BITRATE, 512000);
prefs.setValue(PreferenceConstants.ENCODING_CODEC,
- VideoSharing.Codec.XUGGLER.name());
+ VideoSharing.Codec.IMAGE.name());
prefs.setValue(PreferenceConstants.XUGGLER_CONTAINER_FORMAT, "flv");
prefs.setValue(PreferenceConstants.XUGGLER_CODEC, "libx264");
prefs.setValue(PreferenceConstants.XUGGLER_USE_VBV, false);
prefs.setValue(PreferenceConstants.IMAGE_TILE_CODEC, "png");
prefs.setValue(PreferenceConstants.IMAGE_TILE_QUALITY, 60);
prefs.setValue(PreferenceConstants.IMAGE_TILE_COLORS, 256);
prefs.setValue(PreferenceConstants.IMAGE_TILE_DITHER, true);
prefs.setValue(PreferenceConstants.IMAGE_TILE_SERPENTINE, false);
prefs.setValue(PreferenceConstants.PLAYER_RESAMPLE, false);
prefs.setValue(PreferenceConstants.PLAYER_KEEP_ASPECT_RATIO, true);
prefs.setValue(PreferenceConstants.SCREEN_INITIAL_MODE,
Screen.Mode.FOLLOW_MOUSE.name());
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_QUALITY,
VideoSharingPreferenceHelper.ZOOM_LEVELS[0][1]);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_WIDTH, 320);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_HEIGHT, 240);
prefs.setValue(PreferenceConstants.SCREEN_SHOW_MOUSEPOINTER, true);
}
private static interface PreferenceHolderWrapper {
void setValue(String s, int i);
void setValue(String s, boolean b);
void setValue(String s, String s1);
}
private static class IEclipsePreferencesWrapper implements
PreferenceHolderWrapper {
private IEclipsePreferences preferences;
private IEclipsePreferencesWrapper(IEclipsePreferences preferences) {
this.preferences = preferences;
}
public void setValue(String s, int i) {
preferences.putInt(s, i);
}
public void setValue(String s, boolean b) {
preferences.putBoolean(s, b);
}
public void setValue(String s, String s1) {
preferences.put(s, s1);
}
}
private static class IPreferenceStoreWrapper implements
PreferenceHolderWrapper {
private IPreferenceStore preferenceStore;
private IPreferenceStoreWrapper(IPreferenceStore preferenceStore) {
this.preferenceStore = preferenceStore;
}
public void setValue(String s, int i) {
preferenceStore.setValue(s, i);
}
public void setValue(String s, boolean b) {
preferenceStore.setValue(s, b);
}
public void setValue(String s, String s1) {
preferenceStore.setValue(s, s1);
}
}
}
| false | true | private static void setPreferences(PreferenceHolderWrapper prefs) {
prefs.setValue(PreferenceConstants.GETTING_STARTED_FINISHED, false);
prefs.setValue(PreferenceConstants.ENCRYPT_ACCOUNT, false);
prefs.setValue(PreferenceConstants.AUTO_CONNECT, true);
prefs.setValue(PreferenceConstants.AUTO_PORTMAPPING_DEVICEID, "");
prefs.setValue(PreferenceConstants.GATEWAYCHECKPERFORMED, false);
prefs.setValue(PreferenceConstants.AUTO_FOLLOW_MODE, false);
prefs.setValue(PreferenceConstants.NEEDS_BASED_SYNC, "undefined");
prefs.setValue(PreferenceConstants.SKYPE_USERNAME, "");
prefs.setValue(PreferenceConstants.DEBUG, false);
prefs.setValue(PreferenceConstants.FILE_TRANSFER_PORT, 7777);
prefs.setValue(PreferenceConstants.USE_NEXT_PORTS_FOR_FILE_TRANSFER,
true);
prefs.setValue(PreferenceConstants.LOCAL_SOCKS5_PROXY_DISABLED, false);
prefs.setValue(PreferenceConstants.FORCE_FILETRANSFER_BY_CHAT, false);
prefs.setValue(PreferenceConstants.STUN, "stunserver.org");
prefs.setValue(PreferenceConstants.STUN_PORT, 3478);
prefs.setValue(PreferenceConstants.MILLIS_UPDATE, 300);
prefs.setValue(PreferenceConstants.AUTO_ACCEPT_INVITATION, false);
prefs.setValue(PreferenceConstants.CONCURRENT_UNDO, false);
prefs.setValue(PreferenceConstants.PING_PONG, false);
prefs.setValue(PreferenceConstants.DISABLE_VERSION_CONTROL, false);
// XMPP
prefs.setValue(PreferenceConstants.DEFAULT_XMPP_PORT, 5222);
// InvitationDialog
prefs.setValue(PreferenceConstants.AUTO_CLOSE_DIALOG, true);
prefs.setValue(PreferenceConstants.SKIP_SYNC_SELECTABLE, false);
// its a new workspace per default, is set to false after first start in
// earlyStartup()
prefs.setValue(PreferenceConstants.NEW_WORKSPACE, true);
// Initialize Feedback Preferences
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_DISABLED,
FeedbackManager.FEEDBACK_ENABLED);
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_INTERVAL, 5);
prefs.setValue(PreferenceConstants.STATISTIC_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION_FULL,
AbstractFeedbackManager.FORBID);
// Communication default settings
prefs.setValue(PreferenceConstants.CHATSERVER,
"conference.jabber.ccc.de");
prefs.setValue(PreferenceConstants.USE_DEFAULT_CHATSERVER, true);
prefs.setValue(PreferenceConstants.BEEP_UPON_IM, true);
prefs.setValue(PreferenceConstants.AUDIO_VBR, true);
prefs.setValue(PreferenceConstants.AUDIO_ENABLE_DTX, true);
prefs.setValue(PreferenceConstants.AUDIO_SAMPLERATE, "44100");
prefs.setValue(PreferenceConstants.AUDIO_QUALITY_LEVEL, "8");
// videosharing
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_FRAMERATE, 5);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_RESOLUTION,
VideoSharingPreferenceHelper.RESOLUTIONS[2][1]);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_WIDTH, 320);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_HEIGHT, 240);
prefs.setValue(PreferenceConstants.ENCODING_MAX_BITRATE, 512000);
prefs.setValue(PreferenceConstants.ENCODING_CODEC,
VideoSharing.Codec.XUGGLER.name());
prefs.setValue(PreferenceConstants.XUGGLER_CONTAINER_FORMAT, "flv");
prefs.setValue(PreferenceConstants.XUGGLER_CODEC, "libx264");
prefs.setValue(PreferenceConstants.XUGGLER_USE_VBV, false);
prefs.setValue(PreferenceConstants.IMAGE_TILE_CODEC, "png");
prefs.setValue(PreferenceConstants.IMAGE_TILE_QUALITY, 60);
prefs.setValue(PreferenceConstants.IMAGE_TILE_COLORS, 256);
prefs.setValue(PreferenceConstants.IMAGE_TILE_DITHER, true);
prefs.setValue(PreferenceConstants.IMAGE_TILE_SERPENTINE, false);
prefs.setValue(PreferenceConstants.PLAYER_RESAMPLE, false);
prefs.setValue(PreferenceConstants.PLAYER_KEEP_ASPECT_RATIO, true);
prefs.setValue(PreferenceConstants.SCREEN_INITIAL_MODE,
Screen.Mode.FOLLOW_MOUSE.name());
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_QUALITY,
VideoSharingPreferenceHelper.ZOOM_LEVELS[0][1]);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_WIDTH, 320);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_HEIGHT, 240);
prefs.setValue(PreferenceConstants.SCREEN_SHOW_MOUSEPOINTER, true);
}
| private static void setPreferences(PreferenceHolderWrapper prefs) {
prefs.setValue(PreferenceConstants.GETTING_STARTED_FINISHED, false);
prefs.setValue(PreferenceConstants.ENCRYPT_ACCOUNT, false);
prefs.setValue(PreferenceConstants.AUTO_CONNECT, true);
prefs.setValue(PreferenceConstants.AUTO_PORTMAPPING_DEVICEID, "");
prefs.setValue(PreferenceConstants.GATEWAYCHECKPERFORMED, false);
prefs.setValue(PreferenceConstants.AUTO_FOLLOW_MODE, false);
prefs.setValue(PreferenceConstants.NEEDS_BASED_SYNC, "undefined");
prefs.setValue(PreferenceConstants.SKYPE_USERNAME, "");
prefs.setValue(PreferenceConstants.DEBUG, false);
prefs.setValue(PreferenceConstants.FILE_TRANSFER_PORT, 7777);
prefs.setValue(PreferenceConstants.USE_NEXT_PORTS_FOR_FILE_TRANSFER,
true);
prefs.setValue(PreferenceConstants.LOCAL_SOCKS5_PROXY_DISABLED, false);
prefs.setValue(PreferenceConstants.FORCE_FILETRANSFER_BY_CHAT, false);
prefs.setValue(PreferenceConstants.STUN, "stunserver.org");
prefs.setValue(PreferenceConstants.STUN_PORT, 3478);
prefs.setValue(PreferenceConstants.MILLIS_UPDATE, 300);
prefs.setValue(PreferenceConstants.AUTO_ACCEPT_INVITATION, false);
prefs.setValue(PreferenceConstants.CONCURRENT_UNDO, false);
prefs.setValue(PreferenceConstants.PING_PONG, false);
prefs.setValue(PreferenceConstants.DISABLE_VERSION_CONTROL, false);
// XMPP
prefs.setValue(PreferenceConstants.DEFAULT_XMPP_PORT, 5222);
// InvitationDialog
prefs.setValue(PreferenceConstants.AUTO_CLOSE_DIALOG, true);
prefs.setValue(PreferenceConstants.SKIP_SYNC_SELECTABLE, false);
prefs.setValue(
PreferenceConstants.BUDDYSELECTION_FILTERNONSAROSBUDDIES, true);
// its a new workspace per default, is set to false after first start in
// earlyStartup()
prefs.setValue(PreferenceConstants.NEW_WORKSPACE, true);
// Initialize Feedback Preferences
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_DISABLED,
FeedbackManager.FEEDBACK_ENABLED);
prefs.setValue(PreferenceConstants.FEEDBACK_SURVEY_INTERVAL, 5);
prefs.setValue(PreferenceConstants.STATISTIC_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION,
AbstractFeedbackManager.UNKNOWN);
prefs.setValue(PreferenceConstants.ERROR_LOG_ALLOW_SUBMISSION_FULL,
AbstractFeedbackManager.FORBID);
// Communication default settings
prefs.setValue(PreferenceConstants.CHATSERVER,
"conference.jabber.ccc.de");
prefs.setValue(PreferenceConstants.USE_DEFAULT_CHATSERVER, true);
prefs.setValue(PreferenceConstants.BEEP_UPON_IM, true);
prefs.setValue(PreferenceConstants.AUDIO_VBR, true);
prefs.setValue(PreferenceConstants.AUDIO_ENABLE_DTX, true);
prefs.setValue(PreferenceConstants.AUDIO_SAMPLERATE, "44100");
prefs.setValue(PreferenceConstants.AUDIO_QUALITY_LEVEL, "8");
// videosharing
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_FRAMERATE, 5);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_RESOLUTION,
VideoSharingPreferenceHelper.RESOLUTIONS[2][1]);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_WIDTH, 320);
prefs.setValue(PreferenceConstants.ENCODING_VIDEO_HEIGHT, 240);
prefs.setValue(PreferenceConstants.ENCODING_MAX_BITRATE, 512000);
prefs.setValue(PreferenceConstants.ENCODING_CODEC,
VideoSharing.Codec.IMAGE.name());
prefs.setValue(PreferenceConstants.XUGGLER_CONTAINER_FORMAT, "flv");
prefs.setValue(PreferenceConstants.XUGGLER_CODEC, "libx264");
prefs.setValue(PreferenceConstants.XUGGLER_USE_VBV, false);
prefs.setValue(PreferenceConstants.IMAGE_TILE_CODEC, "png");
prefs.setValue(PreferenceConstants.IMAGE_TILE_QUALITY, 60);
prefs.setValue(PreferenceConstants.IMAGE_TILE_COLORS, 256);
prefs.setValue(PreferenceConstants.IMAGE_TILE_DITHER, true);
prefs.setValue(PreferenceConstants.IMAGE_TILE_SERPENTINE, false);
prefs.setValue(PreferenceConstants.PLAYER_RESAMPLE, false);
prefs.setValue(PreferenceConstants.PLAYER_KEEP_ASPECT_RATIO, true);
prefs.setValue(PreferenceConstants.SCREEN_INITIAL_MODE,
Screen.Mode.FOLLOW_MOUSE.name());
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_QUALITY,
VideoSharingPreferenceHelper.ZOOM_LEVELS[0][1]);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_WIDTH, 320);
prefs.setValue(PreferenceConstants.SCREEN_MOUSE_AREA_HEIGHT, 240);
prefs.setValue(PreferenceConstants.SCREEN_SHOW_MOUSEPOINTER, true);
}
|
diff --git a/src/java/org/infoglue/deliver/taglib/common/TextTransformTag.java b/src/java/org/infoglue/deliver/taglib/common/TextTransformTag.java
index dfbd03b5e..8703d5089 100755
--- a/src/java/org/infoglue/deliver/taglib/common/TextTransformTag.java
+++ b/src/java/org/infoglue/deliver/taglib/common/TextTransformTag.java
@@ -1,260 +1,260 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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 org.infoglue.deliver.taglib.common;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.jsp.JspException;
import org.infoglue.deliver.taglib.TemplateControllerTag;
/**
* This tag help modifying texts in different ways. An example is to html-encode strings or replace all
* whitespaces with or replacing linebreaks with <br/>
*/
public class TextTransformTag extends TemplateControllerTag
{
/**
* The universal version identifier.
*/
private static final long serialVersionUID = 8603406098980150888L;
/**
* The original text.
*/
private String text;
/**
* Should we encode i18n chars
*/
private boolean htmlEncode = false;
/**
* Should we replace linebreaks with something?
*/
private boolean replaceLineBreaks = false;
/**
* The string to replace linebreaks with
*/
private String lineBreakReplacer = "<br/>";
/**
* The linebreak char
*/
private String lineBreakChar = System.getProperty("line.separator");
/**
* What to replace
*/
private String replaceString = null;
/**
* What to replace with
*/
private String replaceWithString = null;
/**
* What to append before the text
*/
private String prefix = null;
/**
* If set - the string must match this to add the prefix
*/
private String addPrefixIfTextMatches = null;
/**
* If set - the string must match this to add the prefix
*/
private String addPrefixIfTextNotMatches = null;
/**
* What to append after the text
*/
private String suffix = null;
/**
* If set - the string must match this to add the suffix
*/
private String addSuffixIfTextMatches = null;
/**
* If set - the string must match this to add the suffix
*/
private String addSuffixIfTextNotMatches = null;
/**
* Default constructor.
*/
public TextTransformTag()
{
super();
}
/**
* Process the end tag. Modifies the string according to settings made.
*
* @return indication of whether to continue evaluating the JSP page.
* @throws JspException if an error occurred while processing this tag.
*/
public int doEndTag() throws JspException
{
String modifiedText = text;
if(replaceString != null && replaceWithString != null)
{
Pattern pattern = Pattern.compile(replaceString);
Matcher matcher = pattern.matcher(modifiedText);
modifiedText = matcher.replaceAll(replaceWithString);
}
if(replaceLineBreaks)
- modifiedText.replaceAll(lineBreakChar, lineBreakReplacer);
+ modifiedText = modifiedText.replaceAll(lineBreakChar, lineBreakReplacer);
if(this.prefix != null)
{
if(this.addPrefixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = this.prefix + modifiedText;
}
else if(this.addPrefixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = this.prefix + modifiedText;
}
else
{
modifiedText = this.prefix + modifiedText;
}
}
if(this.suffix != null)
{
if(this.addSuffixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = modifiedText + this.suffix;
}
else if(this.addSuffixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = modifiedText + this.suffix;
}
else
{
modifiedText = modifiedText + this.suffix;
}
}
if(htmlEncode)
modifiedText = this.getController().getVisualFormatter().escapeHTMLforXMLService(modifiedText);
setResultAttribute(modifiedText);
this.prefix = null;
this.suffix = null;
this.addPrefixIfTextMatches = null;
this.addPrefixIfTextNotMatches = null;
this.addSuffixIfTextMatches = null;
this.addSuffixIfTextNotMatches = null;
return EVAL_PAGE;
}
public void setText(String text) throws JspException
{
this.text = evaluateString("cropText", "text", text);
}
public void setHtmlEncode(boolean htmlEncode)
{
this.htmlEncode = htmlEncode;
}
public void setReplaceLineBreaks(boolean replaceLineBreaks)
{
this.replaceLineBreaks = replaceLineBreaks;
}
public void setLineBreakChar(String lineBreakChar) throws JspException
{
this.lineBreakChar = evaluateString("TextTransform", "lineBreakChar", lineBreakChar);
}
public void setLineBreakReplacer(String lineBreakReplacer) throws JspException
{
this.lineBreakReplacer = evaluateString("TextTransform", "lineBreakReplacer", lineBreakReplacer);
}
public void setReplaceString(String replaceString) throws JspException
{
this.replaceString = evaluateString("TextTransform", "replaceString", replaceString);
}
public void setReplaceWithString(String replaceWithString) throws JspException
{
this.replaceWithString = evaluateString("TextTransform", "replaceWithString", replaceWithString);
}
public void setPrefix(String prefix) throws JspException
{
this.prefix = evaluateString("TextTransform", "prefix", prefix);
}
public void setAddPrefixIfTextMatches(String addPrefixIfTextMatches) throws JspException
{
this.addPrefixIfTextMatches = evaluateString("TextTransform", "addPrefixIfTextMatches", addPrefixIfTextMatches);
}
public void setAddPrefixIfTextNotMatches(String addPrefixIfTextNotMatches) throws JspException
{
this.addPrefixIfTextNotMatches = evaluateString("TextTransform", "addPrefixIfTextNotMatches", addPrefixIfTextNotMatches);
}
public void setSuffix(String suffix) throws JspException
{
this.suffix = evaluateString("TextTransform", "suffix", suffix);
}
public void setAddSuffixIfTextMatches(String addSuffixIfTextMatches) throws JspException
{
this.addSuffixIfTextMatches = evaluateString("TextTransform", "addSuffixIfTextMatches", addSuffixIfTextMatches);
}
public void setAddSuffixIfTextNotMatches(String addSuffixIfTextNotMatches) throws JspException
{
this.addSuffixIfTextNotMatches = evaluateString("TextTransform", "addSuffixIfTextNotMatches", addSuffixIfTextNotMatches);
}
}
| true | true | public int doEndTag() throws JspException
{
String modifiedText = text;
if(replaceString != null && replaceWithString != null)
{
Pattern pattern = Pattern.compile(replaceString);
Matcher matcher = pattern.matcher(modifiedText);
modifiedText = matcher.replaceAll(replaceWithString);
}
if(replaceLineBreaks)
modifiedText.replaceAll(lineBreakChar, lineBreakReplacer);
if(this.prefix != null)
{
if(this.addPrefixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = this.prefix + modifiedText;
}
else if(this.addPrefixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = this.prefix + modifiedText;
}
else
{
modifiedText = this.prefix + modifiedText;
}
}
if(this.suffix != null)
{
if(this.addSuffixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = modifiedText + this.suffix;
}
else if(this.addSuffixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = modifiedText + this.suffix;
}
else
{
modifiedText = modifiedText + this.suffix;
}
}
if(htmlEncode)
modifiedText = this.getController().getVisualFormatter().escapeHTMLforXMLService(modifiedText);
setResultAttribute(modifiedText);
this.prefix = null;
this.suffix = null;
this.addPrefixIfTextMatches = null;
this.addPrefixIfTextNotMatches = null;
this.addSuffixIfTextMatches = null;
this.addSuffixIfTextNotMatches = null;
return EVAL_PAGE;
}
| public int doEndTag() throws JspException
{
String modifiedText = text;
if(replaceString != null && replaceWithString != null)
{
Pattern pattern = Pattern.compile(replaceString);
Matcher matcher = pattern.matcher(modifiedText);
modifiedText = matcher.replaceAll(replaceWithString);
}
if(replaceLineBreaks)
modifiedText = modifiedText.replaceAll(lineBreakChar, lineBreakReplacer);
if(this.prefix != null)
{
if(this.addPrefixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = this.prefix + modifiedText;
}
else if(this.addPrefixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addPrefixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = this.prefix + modifiedText;
}
else
{
modifiedText = this.prefix + modifiedText;
}
}
if(this.suffix != null)
{
if(this.addSuffixIfTextMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(matcher.find())
modifiedText = modifiedText + this.suffix;
}
else if(this.addSuffixIfTextNotMatches != null)
{
Pattern pattern = Pattern.compile(this.addSuffixIfTextNotMatches);
Matcher matcher = pattern.matcher(modifiedText);
if(!matcher.find())
modifiedText = modifiedText + this.suffix;
}
else
{
modifiedText = modifiedText + this.suffix;
}
}
if(htmlEncode)
modifiedText = this.getController().getVisualFormatter().escapeHTMLforXMLService(modifiedText);
setResultAttribute(modifiedText);
this.prefix = null;
this.suffix = null;
this.addPrefixIfTextMatches = null;
this.addPrefixIfTextNotMatches = null;
this.addSuffixIfTextMatches = null;
this.addSuffixIfTextNotMatches = null;
return EVAL_PAGE;
}
|
diff --git a/src/java/org/astrogrid/samp/web/WebHubProfileFactory.java b/src/java/org/astrogrid/samp/web/WebHubProfileFactory.java
index 72f94a5..93f33dc 100644
--- a/src/java/org/astrogrid/samp/web/WebHubProfileFactory.java
+++ b/src/java/org/astrogrid/samp/web/WebHubProfileFactory.java
@@ -1,177 +1,181 @@
package org.astrogrid.samp.web;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import org.astrogrid.samp.hub.HubProfile;
import org.astrogrid.samp.hub.HubProfileFactory;
import org.astrogrid.samp.hub.KeyGenerator;
import org.astrogrid.samp.hub.MessageRestriction;
import org.astrogrid.samp.xmlrpc.internal.InternalServer;
/**
* HubProfileFactory implementation for Web Profile.
*
* @author Mark Taylor
* @since 2 Feb 2011
*/
public class WebHubProfileFactory implements HubProfileFactory {
private static final String logUsage_ = "[-web:log none|http|xml|rpc]";
private static final String authUsage_ =
"[-web:auth swing|true|false|extreme]";
private static final String corsUsage_ = "[-web:[no]cors]";
private static final String flashUsage_ = "[-web:[no]flash]";
private static final String silverlightUsage_ = "[-web:[no]silverlight]";
private static final String urlcontrolUsage_ = "[-web:[no]urlcontrol]";
private static final String restrictMtypeUsage_ =
"[-web:[no]restrictmtypes]";
/**
* Returns "web".
*/
public String getName() {
return "web";
}
public String[] getFlagsUsage() {
return new String[] {
logUsage_,
authUsage_,
corsUsage_,
flashUsage_,
silverlightUsage_,
urlcontrolUsage_,
restrictMtypeUsage_,
};
}
public HubProfile createHubProfile( List flagList ) throws IOException {
// Process flags.
String logType = "none";
String authType = "swing";
boolean useCors = true;
boolean useFlash = true;
boolean useSilverlight = false;
boolean urlControl = true;
boolean restrictMtypes = true;
for ( Iterator it = flagList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.equals( "-web:log" ) ) {
it.remove();
if ( it.hasNext() ) {
logType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: " + logUsage_ );
}
}
else if ( arg.equals( "-web:auth" ) ) {
it.remove();
if ( it.hasNext() ) {
authType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: "
+ authUsage_ );
}
}
else if ( arg.equals( "-web:cors" ) ) {
it.remove();
useCors = true;
}
else if ( arg.equals( "-web:nocors" ) ) {
it.remove();
useCors = false;
}
else if ( arg.equals( "-web:flash" ) ) {
it.remove();
useFlash = true;
}
else if ( arg.equals( "-web:noflash" ) ) {
it.remove();
useFlash = false;
}
else if ( arg.equals( "-web:silverlight" ) ) {
it.remove();
useSilverlight = true;
}
else if ( arg.equals( "-web:nosilverlight" ) ) {
it.remove();
useSilverlight = false;
}
else if ( arg.equals( "-web:urlcontrol" ) ) {
+ it.remove();
urlControl = true;
}
else if ( arg.equals( "-web:nourlcontrol" ) ) {
+ it.remove();
urlControl = false;
}
else if ( arg.equals( "-web:restrictmtypes" ) ) {
+ it.remove();
restrictMtypes = true;
}
else if ( arg.equals( "-web:norestrictmtypes" ) ) {
+ it.remove();
restrictMtypes = false;
}
}
// Prepare HTTP server.
WebHubProfile.ServerFactory sfact = new WebHubProfile.ServerFactory();
try {
sfact.setLogType( logType );
}
catch ( IllegalArgumentException e ) {
throw (IllegalArgumentException)
new IllegalArgumentException( "Unknown log type " + logType
+ "; Usage: " + logUsage_ )
.initCause( e );
}
sfact.setOriginAuthorizer( useCors ? OriginAuthorizers.TRUE
: OriginAuthorizers.FALSE );
sfact.setAllowFlash( useFlash );
sfact.setAllowSilverlight( useSilverlight );
// Prepare client authorizer.
final ClientAuthorizer clientAuth;
if ( "swing".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new HubSwingClientAuthorizer( null ),
Level.INFO, Level.INFO );
}
else if ( "extreme".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new ExtremeSwingClientAuthorizer( null ),
Level.WARNING, Level.INFO );
}
else if ( "true".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.TRUE;
}
else if ( "false".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.FALSE;
}
else {
throw new IllegalArgumentException( "Unknown authorizer type "
+ authType + "; Usage: "
+ authUsage_ );
}
// Prepare subscriptions mask.
MessageRestriction mrestrict = restrictMtypes
? ListMessageRestriction.DEFAULT
: null;
// Construct and return an appropriately configured hub profile.
return new WebHubProfile( sfact, clientAuth, mrestrict,
WebHubProfile.createKeyGenerator(),
urlControl );
}
public Class getHubProfileClass() {
return WebHubProfile.class;
}
}
| false | true | public HubProfile createHubProfile( List flagList ) throws IOException {
// Process flags.
String logType = "none";
String authType = "swing";
boolean useCors = true;
boolean useFlash = true;
boolean useSilverlight = false;
boolean urlControl = true;
boolean restrictMtypes = true;
for ( Iterator it = flagList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.equals( "-web:log" ) ) {
it.remove();
if ( it.hasNext() ) {
logType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: " + logUsage_ );
}
}
else if ( arg.equals( "-web:auth" ) ) {
it.remove();
if ( it.hasNext() ) {
authType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: "
+ authUsage_ );
}
}
else if ( arg.equals( "-web:cors" ) ) {
it.remove();
useCors = true;
}
else if ( arg.equals( "-web:nocors" ) ) {
it.remove();
useCors = false;
}
else if ( arg.equals( "-web:flash" ) ) {
it.remove();
useFlash = true;
}
else if ( arg.equals( "-web:noflash" ) ) {
it.remove();
useFlash = false;
}
else if ( arg.equals( "-web:silverlight" ) ) {
it.remove();
useSilverlight = true;
}
else if ( arg.equals( "-web:nosilverlight" ) ) {
it.remove();
useSilverlight = false;
}
else if ( arg.equals( "-web:urlcontrol" ) ) {
urlControl = true;
}
else if ( arg.equals( "-web:nourlcontrol" ) ) {
urlControl = false;
}
else if ( arg.equals( "-web:restrictmtypes" ) ) {
restrictMtypes = true;
}
else if ( arg.equals( "-web:norestrictmtypes" ) ) {
restrictMtypes = false;
}
}
// Prepare HTTP server.
WebHubProfile.ServerFactory sfact = new WebHubProfile.ServerFactory();
try {
sfact.setLogType( logType );
}
catch ( IllegalArgumentException e ) {
throw (IllegalArgumentException)
new IllegalArgumentException( "Unknown log type " + logType
+ "; Usage: " + logUsage_ )
.initCause( e );
}
sfact.setOriginAuthorizer( useCors ? OriginAuthorizers.TRUE
: OriginAuthorizers.FALSE );
sfact.setAllowFlash( useFlash );
sfact.setAllowSilverlight( useSilverlight );
// Prepare client authorizer.
final ClientAuthorizer clientAuth;
if ( "swing".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new HubSwingClientAuthorizer( null ),
Level.INFO, Level.INFO );
}
else if ( "extreme".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new ExtremeSwingClientAuthorizer( null ),
Level.WARNING, Level.INFO );
}
else if ( "true".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.TRUE;
}
else if ( "false".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.FALSE;
}
else {
throw new IllegalArgumentException( "Unknown authorizer type "
+ authType + "; Usage: "
+ authUsage_ );
}
// Prepare subscriptions mask.
MessageRestriction mrestrict = restrictMtypes
? ListMessageRestriction.DEFAULT
: null;
// Construct and return an appropriately configured hub profile.
return new WebHubProfile( sfact, clientAuth, mrestrict,
WebHubProfile.createKeyGenerator(),
urlControl );
}
| public HubProfile createHubProfile( List flagList ) throws IOException {
// Process flags.
String logType = "none";
String authType = "swing";
boolean useCors = true;
boolean useFlash = true;
boolean useSilverlight = false;
boolean urlControl = true;
boolean restrictMtypes = true;
for ( Iterator it = flagList.iterator(); it.hasNext(); ) {
String arg = (String) it.next();
if ( arg.equals( "-web:log" ) ) {
it.remove();
if ( it.hasNext() ) {
logType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: " + logUsage_ );
}
}
else if ( arg.equals( "-web:auth" ) ) {
it.remove();
if ( it.hasNext() ) {
authType = (String) it.next();
it.remove();
}
else {
throw new IllegalArgumentException( "Usage: "
+ authUsage_ );
}
}
else if ( arg.equals( "-web:cors" ) ) {
it.remove();
useCors = true;
}
else if ( arg.equals( "-web:nocors" ) ) {
it.remove();
useCors = false;
}
else if ( arg.equals( "-web:flash" ) ) {
it.remove();
useFlash = true;
}
else if ( arg.equals( "-web:noflash" ) ) {
it.remove();
useFlash = false;
}
else if ( arg.equals( "-web:silverlight" ) ) {
it.remove();
useSilverlight = true;
}
else if ( arg.equals( "-web:nosilverlight" ) ) {
it.remove();
useSilverlight = false;
}
else if ( arg.equals( "-web:urlcontrol" ) ) {
it.remove();
urlControl = true;
}
else if ( arg.equals( "-web:nourlcontrol" ) ) {
it.remove();
urlControl = false;
}
else if ( arg.equals( "-web:restrictmtypes" ) ) {
it.remove();
restrictMtypes = true;
}
else if ( arg.equals( "-web:norestrictmtypes" ) ) {
it.remove();
restrictMtypes = false;
}
}
// Prepare HTTP server.
WebHubProfile.ServerFactory sfact = new WebHubProfile.ServerFactory();
try {
sfact.setLogType( logType );
}
catch ( IllegalArgumentException e ) {
throw (IllegalArgumentException)
new IllegalArgumentException( "Unknown log type " + logType
+ "; Usage: " + logUsage_ )
.initCause( e );
}
sfact.setOriginAuthorizer( useCors ? OriginAuthorizers.TRUE
: OriginAuthorizers.FALSE );
sfact.setAllowFlash( useFlash );
sfact.setAllowSilverlight( useSilverlight );
// Prepare client authorizer.
final ClientAuthorizer clientAuth;
if ( "swing".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new HubSwingClientAuthorizer( null ),
Level.INFO, Level.INFO );
}
else if ( "extreme".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers
.createLoggingClientAuthorizer(
new ExtremeSwingClientAuthorizer( null ),
Level.WARNING, Level.INFO );
}
else if ( "true".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.TRUE;
}
else if ( "false".equalsIgnoreCase( authType ) ) {
clientAuth = ClientAuthorizers.FALSE;
}
else {
throw new IllegalArgumentException( "Unknown authorizer type "
+ authType + "; Usage: "
+ authUsage_ );
}
// Prepare subscriptions mask.
MessageRestriction mrestrict = restrictMtypes
? ListMessageRestriction.DEFAULT
: null;
// Construct and return an appropriately configured hub profile.
return new WebHubProfile( sfact, clientAuth, mrestrict,
WebHubProfile.createKeyGenerator(),
urlControl );
}
|
diff --git a/src/org/apache/xalan/transformer/TransformerIdentityImpl.java b/src/org/apache/xalan/transformer/TransformerIdentityImpl.java
index 55ac1f3f..583e0767 100644
--- a/src/org/apache/xalan/transformer/TransformerIdentityImpl.java
+++ b/src/org/apache/xalan/transformer/TransformerIdentityImpl.java
@@ -1,1446 +1,1446 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xalan.transformer;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.apache.xml.serializer.Serializer;
import org.apache.xml.serializer.SerializerFactory;
import org.apache.xml.serializer.Method;
import org.apache.xalan.res.XSLMessages;
import org.apache.xalan.res.XSLTErrorResources;
import org.apache.xalan.templates.OutputProperties;
import org.apache.xml.utils.DOMBuilder;
import org.apache.xml.utils.TreeWalker;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DeclHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* This class implements an identity transformer for
* {@link javax.xml.transform.sax.SAXTransformerFactory#newTransformerHandler()
* and {@link javax.xml.transform.TransformerFactory#newTransformer()}. It
* simply feeds SAX events directly to a serializer ContentHandler, if the
* result is a stream. If the result is a DOM, it will send the events to
* {@link org.apache.xml.utils.DOMBuilder}. If the result is another
* content handler, it will simply pass the events on.
*/
public class TransformerIdentityImpl extends Transformer
implements TransformerHandler, DeclHandler
{
/**
* Constructor TransformerIdentityImpl creates an identity transform.
*
*/
public TransformerIdentityImpl()
{
m_outputFormat = new OutputProperties(Method.XML);
}
/**
* Enables the user of the TransformerHandler to set the
* to set the Result for the transformation.
*
* @param result A Result instance, should not be null.
*
* @throws IllegalArgumentException if result is invalid for some reason.
*/
public void setResult(Result result) throws IllegalArgumentException
{
if(null == result)
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"Result should not be null");
m_result = result;
}
/**
* Set the base ID (URI or system ID) from where relative
* URLs will be resolved.
* @param systemID Base URI for the source tree.
*/
public void setSystemId(String systemID)
{
m_systemID = systemID;
}
/**
* Get the base ID (URI or system ID) from where relative
* URLs will be resolved.
* @return The systemID that was set with {@link #setSystemId}.
*/
public String getSystemId()
{
return m_systemID;
}
/**
* Get the Transformer associated with this handler, which
* is needed in order to set parameters and output properties.
*
* @return non-null reference to the transformer.
*/
public Transformer getTransformer()
{
return this;
}
/**
* Create a result ContentHandler from a Result object, based
* on the current OutputProperties.
*
* @param outputTarget Where the transform result should go,
* should not be null.
*
* @return A valid ContentHandler that will create the
* result tree when it is fed SAX events.
*
* @throws TransformerException
*/
private void createResultContentHandler(Result outputTarget)
throws TransformerException
{
if (outputTarget instanceof SAXResult)
{
SAXResult saxResult = (SAXResult) outputTarget;
m_resultContentHandler = saxResult.getHandler();
m_resultLexicalHandler = saxResult.getLexicalHandler();
if (m_resultContentHandler instanceof Serializer)
{
// Dubious but needed, I think.
m_serializer = (Serializer) m_resultContentHandler;
}
}
else if (outputTarget instanceof DOMResult)
{
DOMResult domResult = (DOMResult) outputTarget;
Node outputNode = domResult.getNode();
Document doc;
short type;
if (null != outputNode)
{
type = outputNode.getNodeType();
doc = (Node.DOCUMENT_NODE == type)
? (Document) outputNode : outputNode.getOwnerDocument();
}
else
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
}
catch (ParserConfigurationException pce)
{
throw new TransformerException(pce);
}
outputNode = doc;
type = outputNode.getNodeType();
((DOMResult) outputTarget).setNode(outputNode);
}
m_resultContentHandler =
(Node.DOCUMENT_FRAGMENT_NODE == type)
? new DOMBuilder(doc, (DocumentFragment) outputNode)
: new DOMBuilder(doc, outputNode);
m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
}
else if (outputTarget instanceof StreamResult)
{
StreamResult sresult = (StreamResult) outputTarget;
String method = m_outputFormat.getProperty(OutputKeys.METHOD);
try
{
Serializer serializer =
SerializerFactory.getSerializer(m_outputFormat.getProperties());
m_serializer = serializer;
if (null != sresult.getWriter())
serializer.setWriter(sresult.getWriter());
else if (null != sresult.getOutputStream())
serializer.setOutputStream(sresult.getOutputStream());
else if (null != sresult.getSystemId())
{
String fileURL = sresult.getSystemId();
if (fileURL.startsWith("file:///"))
{
if (fileURL.substring(8).indexOf(":") >0)
fileURL = fileURL.substring(8);
else
fileURL = fileURL.substring(7);
}
m_outputStream = new java.io.FileOutputStream(fileURL);
serializer.setOutputStream(m_outputStream);
}
else
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_OUTPUT_SPECIFIED, null)); //"No output specified!");
m_resultContentHandler = serializer.asContentHandler();
}
catch (IOException ioe)
{
throw new TransformerException(ioe);
}
}
else
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, new Object[]{outputTarget.getClass().getName()})); //"Can't transform to a Result of type "
// + outputTarget.getClass().getName()
// + "!");
}
if (m_resultContentHandler instanceof DTDHandler)
m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
if (m_resultContentHandler instanceof DeclHandler)
m_resultDeclHandler = (DeclHandler) m_resultContentHandler;
if (m_resultContentHandler instanceof LexicalHandler)
m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
}
/**
* Process the source tree to the output result.
* @param source The input for the source tree.
*
* @param outputTarget The output target.
*
* @throws TransformerException If an unrecoverable error occurs
* during the course of the transformation.
*/
public void transform(Source source, Result outputTarget)
throws TransformerException
{
createResultContentHandler(outputTarget);
try
{
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId();
Node dNode = dsource.getNode();
if (null != dNode)
{
try
{
- if(dNode.getNodeType() != Node.DOCUMENT_NODE)
+ if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.startDocument();
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
{
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length);
}
else
{
TreeWalker walker = new TreeWalker(this, new org.apache.xml.utils.DOM2Helper(), m_systemID);
walker.traverse(dNode);
}
}
finally
{
- if(dNode.getNodeType() != Node.DOCUMENT_NODE)
+ if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.endDocument();
}
}
catch (SAXException se)
{
throw new TransformerException(se);
}
return;
}
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource)
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
try
{
XMLReader reader = null;
if (source instanceof SAXSource)
reader = ((SAXSource) source).getXMLReader();
if (null == reader)
{
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
}
catch (org.xml.sax.SAXException se)
{
// We don't care.
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler);
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty(
"http://xml.org/sax/properties/declaration-handler",
inputHandler);
}
catch (org.xml.sax.SAXException se){}
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
inputHandler);
}
catch (org.xml.sax.SAXNotRecognizedException snre){}
reader.parse(xmlSource);
}
catch (org.apache.xml.utils.WrappedRuntimeException wre)
{
Throwable throwable = wre.getException();
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
throw new TransformerException(wre.getException());
}
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se);
}
catch (IOException ioe)
{
throw new TransformerException(ioe);
}
}
finally
{
if(null != m_outputStream)
{
try
{
m_outputStream.close();
}
catch(IOException ioe){}
m_outputStream = null;
}
}
}
/**
* Add a parameter for the transformation.
*
* <p>Pass a qualified name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the first
* character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
* no prefix is used.</p>
*
* @param name The name of the parameter, which may begin with a namespace URI
* in curly braces ({}).
* @param value The value object. This can be any valid Java object. It is
* up to the processor to provide the proper object coersion or to simply
* pass the object on for use in an extension.
*/
public void setParameter(String name, Object value)
{
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
}
/**
* Get a parameter that was explicitly set with setParameter
* or setParameters.
*
* <p>This method does not return a default parameter value, which
* cannot be determined until the node context is evaluated during
* the transformation process.
*
*
* @param name Name of the parameter.
* @return A parameter that has been set with setParameter.
*/
public Object getParameter(String name)
{
if (null == m_params)
return null;
return m_params.get(name);
}
/**
* Clear all parameters set with setParameter.
*/
public void clearParameters()
{
if (null == m_params)
return;
m_params.clear();
}
/**
* Set an object that will be used to resolve URIs used in
* document().
*
* <p>If the resolver argument is null, the URIResolver value will
* be cleared, and the default behavior will be used.</p>
*
* @param resolver An object that implements the URIResolver interface,
* or null.
*/
public void setURIResolver(URIResolver resolver)
{
m_URIResolver = resolver;
}
/**
* Get an object that will be used to resolve URIs used in
* document(), etc.
*
* @return An object that implements the URIResolver interface,
* or null.
*/
public URIResolver getURIResolver()
{
return m_URIResolver;
}
/**
* Set the output properties for the transformation. These
* properties will override properties set in the Templates
* with xsl:output.
*
* <p>If argument to this function is null, any properties
* previously set are removed, and the value will revert to the value
* defined in the templates object.</p>
*
* <p>Pass a qualified property key name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the first
* character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
* no prefix is used.</p>
*
* @param oformat A set of output properties that will be
* used to override any of the same properties in affect
* for the transformation.
*
* @see javax.xml.transform.OutputKeys
* @see java.util.Properties
*
* @throws IllegalArgumentException if any of the argument keys are not
* recognized and are not namespace qualified.
*/
public void setOutputProperties(Properties oformat)
throws IllegalArgumentException
{
if (null != oformat)
{
// See if an *explicit* method was set.
String method = (String) oformat.get(OutputKeys.METHOD);
if (null != method)
m_outputFormat = new OutputProperties(method);
else
m_outputFormat = new OutputProperties();
}
if (null != oformat)
{
m_outputFormat.copyFrom(oformat);
}
}
/**
* Get a copy of the output properties for the transformation.
*
* <p>The properties returned should contain properties set by the user,
* and properties set by the stylesheet, and these properties
* are "defaulted" by default properties specified by <a href="http://www.w3.org/TR/xslt#output">section 16 of the
* XSL Transformations (XSLT) W3C Recommendation</a>. The properties that
* were specifically set by the user or the stylesheet should be in the base
* Properties list, while the XSLT default properties that were not
* specifically set should be the default Properties list. Thus,
* getOutputProperties().getProperty(String key) will obtain any
* property in that was set by {@link #setOutputProperty},
* {@link #setOutputProperties}, in the stylesheet, <em>or</em> the default
* properties, while
* getOutputProperties().get(String key) will only retrieve properties
* that were explicitly set by {@link #setOutputProperty},
* {@link #setOutputProperties}, or in the stylesheet.</p>
*
* <p>Note that mutation of the Properties object returned will not
* effect the properties that the transformation contains.</p>
*
* <p>If any of the argument keys are not recognized and are not
* namespace qualified, the property will be ignored. In other words the
* behaviour is not orthogonal with setOutputProperties.</p>
*
* @return A copy of the set of output properties in effect
* for the next transformation.
*
* @see javax.xml.transform.OutputKeys
* @see java.util.Properties
*/
public Properties getOutputProperties()
{
return (Properties) m_outputFormat.getProperties().clone();
}
/**
* Set an output property that will be in effect for the
* transformation.
*
* <p>Pass a qualified property name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the first
* character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
* no prefix is used.</p>
*
* <p>The Properties object that was passed to {@link #setOutputProperties} won't
* be effected by calling this method.</p>
*
* @param name A non-null String that specifies an output
* property name, which may be namespace qualified.
* @param value The non-null string value of the output property.
*
* @throws IllegalArgumentException If the property is not supported, and is
* not qualified with a namespace.
*
* @see javax.xml.transform.OutputKeys
*/
public void setOutputProperty(String name, String value)
throws IllegalArgumentException
{
if (!m_outputFormat.isLegalPropertyKey(name))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
//+ name);
m_outputFormat.setProperty(name, value);
}
/**
* Get an output property that is in effect for the
* transformation. The property specified may be a property
* that was set with setOutputProperty, or it may be a
* property specified in the stylesheet.
*
* @param name A non-null String that specifies an output
* property name, which may be namespace qualified.
*
* @return The string value of the output property, or null
* if no property was found.
*
* @throws IllegalArgumentException If the property is not supported.
*
* @see javax.xml.transform.OutputKeys
*/
public String getOutputProperty(String name) throws IllegalArgumentException
{
String value = null;
OutputProperties props = m_outputFormat;
value = props.getProperty(name);
if (null == value)
{
if (!props.isLegalPropertyKey(name))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
// + name);
}
return value;
}
/**
* Set the error event listener in effect for the transformation.
*
* @param listener The new error listener.
* @throws IllegalArgumentException if listener is null.
*/
public void setErrorListener(ErrorListener listener)
throws IllegalArgumentException
{
if (listener == null)
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_NULL_ERROR_HANDLER, null));
else
m_errorListener = listener;
}
/**
* Get the error event handler in effect for the transformation.
*
* @return The current error handler, which should never be null.
*/
public ErrorListener getErrorListener()
{
return m_errorListener;
}
////////////////////////////////////////////////////////////////////
// Default implementation of DTDHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive notification of a notation declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to keep track of the notations
* declared in a document.</p>
*
* @param name The notation name.
* @param publicId The notation public identifier, or null if not
* available.
* @param systemId The notation system identifier.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#notationDecl
*
* @throws SAXException
*/
public void notationDecl(String name, String publicId, String systemId)
throws SAXException
{
if (null != m_resultDTDHandler)
m_resultDTDHandler.notationDecl(name, publicId, systemId);
}
/**
* Receive notification of an unparsed entity declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to keep track of the unparsed entities
* declared in a document.</p>
*
* @param name The entity name.
* @param publicId The entity public identifier, or null if not
* available.
* @param systemId The entity system identifier.
* @param notationName The name of the associated notation.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*
* @throws SAXException
*/
public void unparsedEntityDecl(
String name, String publicId, String systemId, String notationName)
throws SAXException
{
if (null != m_resultDTDHandler)
m_resultDTDHandler.unparsedEntityDecl(name, publicId, systemId,
notationName);
}
////////////////////////////////////////////////////////////////////
// Default implementation of ContentHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive a Locator object for document events.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to store the locator for use
* with other document events.</p>
*
* @param locator A locator for all SAX document events.
* @see org.xml.sax.ContentHandler#setDocumentLocator
* @see org.xml.sax.Locator
*/
public void setDocumentLocator(Locator locator)
{
try
{
if (null == m_resultContentHandler)
createResultContentHandler(m_result);
}
catch (TransformerException te)
{
throw new org.apache.xml.utils.WrappedRuntimeException(te);
}
m_resultContentHandler.setDocumentLocator(locator);
}
/**
* Receive notification of the beginning of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the beginning
* of a document (such as allocating the root node of a tree or
* creating an output file).</p>
*
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startDocument
*
* @throws SAXException
*/
public void startDocument() throws SAXException
{
try
{
if (null == m_resultContentHandler)
createResultContentHandler(m_result);
}
catch (TransformerException te)
{
throw new SAXException(te.getMessage(), te);
}
// Reset for multiple transforms with this transformer.
m_flushedStartDoc = false;
m_foundFirstElement = false;
}
boolean m_flushedStartDoc = false;
protected final void flushStartDoc()
throws SAXException
{
if(!m_flushedStartDoc)
{
if (m_resultContentHandler == null)
{
try
{
createResultContentHandler(m_result);
}
catch(TransformerException te)
{
throw new SAXException(te);
}
}
m_resultContentHandler.startDocument();
m_flushedStartDoc = true;
}
}
/**
* Receive notification of the end of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end
* of a document (such as finalising a tree or closing an output
* file).</p>
*
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endDocument
*
* @throws SAXException
*/
public void endDocument() throws SAXException
{
flushStartDoc();
m_resultContentHandler.endDocument();
}
/**
* Receive notification of the start of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each Namespace prefix scope (such as storing the prefix mapping).</p>
*
* @param prefix The Namespace prefix being declared.
* @param uri The Namespace URI mapped to the prefix.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startPrefixMapping
*
* @throws SAXException
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.startPrefixMapping(prefix, uri);
}
/**
* Receive notification of the end of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each prefix mapping.</p>
*
* @param prefix The Namespace prefix being declared.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endPrefixMapping
*
* @throws SAXException
*/
public void endPrefixMapping(String prefix) throws SAXException
{
flushStartDoc();
m_resultContentHandler.endPrefixMapping(prefix);
}
/**
* Receive notification of the start of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each element (such as allocating a new tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @param attributes The specified or defaulted attributes.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startElement
*
* @throws SAXException
*/
public void startElement(
String uri, String localName, String qName, Attributes attributes)
throws SAXException
{
if (!m_foundFirstElement && null != m_serializer)
{
m_foundFirstElement = true;
Serializer newSerializer;
try
{
newSerializer = SerializerSwitcher.switchSerializerIfHTML(uri,
localName, m_outputFormat.getProperties(), m_serializer);
}
catch (TransformerException te)
{
throw new SAXException(te);
}
if (newSerializer != m_serializer)
{
try
{
m_resultContentHandler = newSerializer.asContentHandler();
}
catch (IOException ioe) // why?
{
throw new SAXException(ioe);
}
if (m_resultContentHandler instanceof DTDHandler)
m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
if (m_resultContentHandler instanceof LexicalHandler)
m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
m_serializer = newSerializer;
}
}
flushStartDoc();
m_resultContentHandler.startElement(uri, localName, qName, attributes);
}
/**
* Receive notification of the end of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each element (such as finalising a tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @param attributes The specified or defaulted attributes.
*
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endElement
*
* @throws SAXException
*/
public void endElement(String uri, String localName, String qName)
throws SAXException
{
m_resultContentHandler.endElement(uri, localName, qName);
}
/**
* Receive notification of character data inside an element.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of character data
* (such as adding the data to a node or buffer, or printing it to
* a file).</p>
*
* @param ch The characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#characters
*
* @throws SAXException
*/
public void characters(char ch[], int start, int length) throws SAXException
{
flushStartDoc();
m_resultContentHandler.characters(ch, start, length);
}
/**
* Receive notification of ignorable whitespace in element content.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of ignorable
* whitespace (such as adding data to a node or buffer, or printing
* it to a file).</p>
*
* @param ch The whitespace characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#ignorableWhitespace
*
* @throws SAXException
*/
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException
{
m_resultContentHandler.ignorableWhitespace(ch, start, length);
}
/**
* Receive notification of a processing instruction.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param target The processing instruction target.
* @param data The processing instruction data, or null if
* none is supplied.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*
* @throws SAXException
*/
public void processingInstruction(String target, String data)
throws SAXException
{
flushStartDoc();
m_resultContentHandler.processingInstruction(target, data);
}
/**
* Receive notification of a skipped entity.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param name The name of the skipped entity.
* @throws org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*
* @throws SAXException
*/
public void skippedEntity(String name) throws SAXException
{
flushStartDoc();
m_resultContentHandler.skippedEntity(name);
}
/**
* Report the start of DTD declarations, if any.
*
* <p>Any declarations are assumed to be in the internal subset
* unless otherwise indicated by a {@link #startEntity startEntity}
* event.</p>
*
* <p>Note that the start/endDTD events will appear within
* the start/endDocument events from ContentHandler and
* before the first startElement event.</p>
*
* @param name The document type name.
* @param publicId The declared public identifier for the
* external DTD subset, or null if none was declared.
* @param systemId The declared system identifier for the
* external DTD subset, or null if none was declared.
* @throws SAXException The application may raise an
* exception.
* @see #endDTD
* @see #startEntity
*/
public void startDTD(String name, String publicId, String systemId)
throws SAXException
{
flushStartDoc();
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startDTD(name, publicId, systemId);
}
/**
* Report the end of DTD declarations.
*
* @throws SAXException The application may raise an exception.
* @see #startDTD
*/
public void endDTD() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endDTD();
}
/**
* Report the beginning of an entity in content.
*
* <p><strong>NOTE:</entity> entity references in attribute
* values -- and the start and end of the document entity --
* are never reported.</p>
*
* <p>The start and end of the external DTD subset are reported
* using the pseudo-name "[dtd]". All other events must be
* properly nested within start/end entity events.</p>
*
* <p>Note that skipped entities will be reported through the
* {@link org.xml.sax.ContentHandler#skippedEntity skippedEntity}
* event, which is part of the ContentHandler interface.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @throws SAXException The application may raise an exception.
* @see #endEntity
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl
*/
public void startEntity(String name) throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startEntity(name);
}
/**
* Report the end of an entity.
*
* @param name The name of the entity that is ending.
* @throws SAXException The application may raise an exception.
* @see #startEntity
*/
public void endEntity(String name) throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endEntity(name);
}
/**
* Report the start of a CDATA section.
*
* <p>The contents of the CDATA section will be reported through
* the regular {@link org.xml.sax.ContentHandler#characters
* characters} event.</p>
*
* @throws SAXException The application may raise an exception.
* @see #endCDATA
*/
public void startCDATA() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.startCDATA();
}
/**
* Report the end of a CDATA section.
*
* @throws SAXException The application may raise an exception.
* @see #startCDATA
*/
public void endCDATA() throws SAXException
{
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.endCDATA();
}
/**
* Report an XML comment anywhere in the document.
*
* <p>This callback will be used for comments inside or outside the
* document element, including comments in the external DTD
* subset (if read).</p>
*
* @param ch An array holding the characters in the comment.
* @param start The starting position in the array.
* @param length The number of characters to use from the array.
* @throws SAXException The application may raise an exception.
*/
public void comment(char ch[], int start, int length) throws SAXException
{
flushStartDoc();
if (null != m_resultLexicalHandler)
m_resultLexicalHandler.comment(ch, start, length);
}
// Implement DeclHandler
/**
* Report an element type declaration.
*
* <p>The content model will consist of the string "EMPTY", the
* string "ANY", or a parenthesised group, optionally followed
* by an occurrence indicator. The model will be normalized so
* that all whitespace is removed,and will include the enclosing
* parentheses.</p>
*
* @param name The element type name.
* @param model The content model as a normalized string.
* @exception SAXException The application may raise an exception.
*/
public void elementDecl (String name, String model)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.elementDecl(name, model);
}
/**
* Report an attribute type declaration.
*
* <p>Only the effective (first) declaration for an attribute will
* be reported. The type will be one of the strings "CDATA",
* "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
* "ENTITIES", or "NOTATION", or a parenthesized token group with
* the separator "|" and all whitespace removed.</p>
*
* @param eName The name of the associated element.
* @param aName The name of the attribute.
* @param type A string representing the attribute type.
* @param valueDefault A string representing the attribute default
* ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if
* none of these applies.
* @param value A string representing the attribute's default value,
* or null if there is none.
* @exception SAXException The application may raise an exception.
*/
public void attributeDecl (String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.attributeDecl(eName, aName, type, valueDefault, value);
}
/**
* Report an internal entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param value The replacement text of the entity.
* @exception SAXException The application may raise an exception.
* @see #externalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void internalEntityDecl (String name, String value)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.internalEntityDecl(name, value);
}
/**
* Report a parsed external entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param publicId The declared public identifier of the entity, or
* null if none was declared.
* @param systemId The declared system identifier of the entity.
* @exception SAXException The application may raise an exception.
* @see #internalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void externalEntityDecl (String name, String publicId,
String systemId)
throws SAXException
{
if (null != m_resultDeclHandler)
m_resultDeclHandler.externalEntityDecl(name, publicId, systemId);
}
/**
* This is null unless we own the stream.
*/
private java.io.FileOutputStream m_outputStream = null;
/** The content handler where result events will be sent. */
private ContentHandler m_resultContentHandler;
/** The lexical handler where result events will be sent. */
private LexicalHandler m_resultLexicalHandler;
/** The DTD handler where result events will be sent. */
private DTDHandler m_resultDTDHandler;
/** The Decl handler where result events will be sent. */
private DeclHandler m_resultDeclHandler;
/** The Serializer, which may or may not be null. */
private Serializer m_serializer;
/** The Result object. */
private Result m_result;
/**
* The system ID, which is unused, but must be returned to fullfill the
* TransformerHandler interface.
*/
private String m_systemID;
/**
* The parameters, which is unused, but must be returned to fullfill the
* Transformer interface.
*/
private Hashtable m_params;
/** The error listener for TrAX errors and warnings. */
private ErrorListener m_errorListener =
new org.apache.xml.utils.DefaultErrorHandler();
/**
* The URIResolver, which is unused, but must be returned to fullfill the
* TransformerHandler interface.
*/
URIResolver m_URIResolver;
/** The output properties. */
private OutputProperties m_outputFormat;
/** Flag to set if we've found the first element, so we can tell if we have
* to check to see if we should create an HTML serializer. */
boolean m_foundFirstElement;
}
| false | true | public void transform(Source source, Result outputTarget)
throws TransformerException
{
createResultContentHandler(outputTarget);
try
{
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId();
Node dNode = dsource.getNode();
if (null != dNode)
{
try
{
if(dNode.getNodeType() != Node.DOCUMENT_NODE)
this.startDocument();
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
{
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length);
}
else
{
TreeWalker walker = new TreeWalker(this, new org.apache.xml.utils.DOM2Helper(), m_systemID);
walker.traverse(dNode);
}
}
finally
{
if(dNode.getNodeType() != Node.DOCUMENT_NODE)
this.endDocument();
}
}
catch (SAXException se)
{
throw new TransformerException(se);
}
return;
}
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource)
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
try
{
XMLReader reader = null;
if (source instanceof SAXSource)
reader = ((SAXSource) source).getXMLReader();
if (null == reader)
{
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
}
catch (org.xml.sax.SAXException se)
{
// We don't care.
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler);
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty(
"http://xml.org/sax/properties/declaration-handler",
inputHandler);
}
catch (org.xml.sax.SAXException se){}
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
inputHandler);
}
catch (org.xml.sax.SAXNotRecognizedException snre){}
reader.parse(xmlSource);
}
catch (org.apache.xml.utils.WrappedRuntimeException wre)
{
Throwable throwable = wre.getException();
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
throw new TransformerException(wre.getException());
}
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se);
}
catch (IOException ioe)
{
throw new TransformerException(ioe);
}
}
finally
{
if(null != m_outputStream)
{
try
{
m_outputStream.close();
}
catch(IOException ioe){}
m_outputStream = null;
}
}
}
| public void transform(Source source, Result outputTarget)
throws TransformerException
{
createResultContentHandler(outputTarget);
try
{
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId();
Node dNode = dsource.getNode();
if (null != dNode)
{
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.startDocument();
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
{
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length);
}
else
{
TreeWalker walker = new TreeWalker(this, new org.apache.xml.utils.DOM2Helper(), m_systemID);
walker.traverse(dNode);
}
}
finally
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.endDocument();
}
}
catch (SAXException se)
{
throw new TransformerException(se);
}
return;
}
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource)
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
try
{
XMLReader reader = null;
if (source instanceof SAXSource)
reader = ((SAXSource) source).getXMLReader();
if (null == reader)
{
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
}
catch (org.xml.sax.SAXException se)
{
// We don't care.
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler);
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty(
"http://xml.org/sax/properties/declaration-handler",
inputHandler);
}
catch (org.xml.sax.SAXException se){}
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
inputHandler);
}
catch (org.xml.sax.SAXNotRecognizedException snre){}
reader.parse(xmlSource);
}
catch (org.apache.xml.utils.WrappedRuntimeException wre)
{
Throwable throwable = wre.getException();
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
throw new TransformerException(wre.getException());
}
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se);
}
catch (IOException ioe)
{
throw new TransformerException(ioe);
}
}
finally
{
if(null != m_outputStream)
{
try
{
m_outputStream.close();
}
catch(IOException ioe){}
m_outputStream = null;
}
}
}
|
diff --git a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsCoreValidator.java b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsCoreValidator.java
index 854f054e9..690d1d2c9 100644
--- a/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsCoreValidator.java
+++ b/struts/plugins/org.jboss.tools.struts/src/org/jboss/tools/struts/validation/StrutsCoreValidator.java
@@ -1,275 +1,278 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.struts.validation;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.validation.internal.core.ValidationException;
import org.eclipse.wst.validation.internal.provisional.core.IReporter;
import org.jboss.tools.common.model.XModelObject;
import org.jboss.tools.common.model.util.EclipseResourceUtil;
import org.jboss.tools.common.validation.ContextValidationHelper;
import org.jboss.tools.common.validation.IProjectValidationContext;
import org.jboss.tools.common.validation.IValidatingProjectSet;
import org.jboss.tools.common.validation.IValidatingProjectTree;
import org.jboss.tools.common.validation.IValidator;
import org.jboss.tools.common.validation.ValidationErrorManager;
import org.jboss.tools.common.validation.ValidatorManager;
import org.jboss.tools.common.validation.internal.ProjectValidationContext;
import org.jboss.tools.common.validation.internal.SimpleValidatingProjectTree;
import org.jboss.tools.common.validation.internal.ValidatingProjectSet;
import org.jboss.tools.common.web.WebUtils;
import org.jboss.tools.jst.web.WebModelPlugin;
import org.jboss.tools.jst.web.model.helpers.WebAppHelper;
import org.jboss.tools.jst.web.validation.Check;
import org.jboss.tools.struts.StrutsConstants;
import org.jboss.tools.struts.StrutsModelPlugin;
import org.jboss.tools.struts.StrutsProject;
/**
* @author Viacheslav Kabanovich
*/
public class StrutsCoreValidator extends ValidationErrorManager implements IValidator, StrutsConstants {
public static final String ID = "org.jboss.tools.struts.validation.StrutsCoreValidator"; //$NON-NLS-1$
public static final String PROBLEM_TYPE = "org.jboss.tools.struts.strutsproblem"; //$NON-NLS-1$
public static final String PREFERENCE_PAGE_ID = "org.jboss.tools.struts.ui.StrutsValidatorPreferencePage"; //$NON-NLS-1$
public static String SHORT_ID = "verification"; //$NON-NLS-1$
static String XML_EXT = ".xml"; //$NON-NLS-1$
String projectName;
Map<IProject, IProjectValidationContext> contexts = new HashMap<IProject, IProjectValidationContext>();
Map<String, Set<Check>> checks = new HashMap<String, Set<Check>>();
public StrutsCoreValidator() {
createChecks();
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#getPreference(org.eclipse.core.resources.IProject, java.lang.String)
*/
@Override
protected String getPreference(IProject project, String preferenceKey) {
return StrutsPreferences.getInstance().getProjectPreference(project, preferenceKey);
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#getMaxNumberOfMarkersPerFile(org.eclipse.core.resources.IProject)
*/
@Override
public int getMaxNumberOfMarkersPerFile(IProject project) {
return StrutsPreferences.getMaxNumberOfProblemMarkersPerFile(project);
}
private void addCheck(Check check, String... entities) {
for (String entity: entities) {
Set<Check> cs = checks.get(entity);
if(cs == null) {
cs = new HashSet<Check>();
checks.put(entity, cs);
}
cs.add(check);
}
}
void createChecks() {
addCheck(new ActionForwardCheck(this, StrutsPreferences.INVALID_ACTION_FORWARD),
ENT_FORWARD + VER_SUFFIX_10, ENT_FORWARD + VER_SUFFIX_11, ENT_FORWARD + VER_SUFFIX_12);
addCheck(new ActionNameCheck(this, StrutsPreferences.INVALID_ACTION_NAME),
ENT_ACTION + VER_SUFFIX_10, ENT_ACTION + VER_SUFFIX_11, ENT_ACTION + VER_SUFFIX_12);
addCheck(new ActionRefsCheck(this, StrutsPreferences.INVALID_ACTION_REFERENCE_ATTRIBUTE),
ENT_ACTION + VER_SUFFIX_10, ENT_ACTION + VER_SUFFIX_11, ENT_ACTION + VER_SUFFIX_12);
addCheck(new ActionTypeCheck(this, StrutsPreferences.INVALID_ACTION_TYPE),
ENT_ACTION + VER_SUFFIX_10, ENT_ACTION + VER_SUFFIX_11, ENT_ACTION + VER_SUFFIX_12);
addCheck(new GlobalExceptionCheck(this, StrutsPreferences.INVALID_GLOBAL_EXCEPTION),
ENT_EXCEPTION + VER_SUFFIX_11);
addCheck(new GlobalForwardCheck(this, StrutsPreferences.INVALID_GLOBAL_FORWARD),
ENT_FORWARD + VER_SUFFIX_10, ENT_FORWARD + VER_SUFFIX_11, ENT_FORWARD + VER_SUFFIX_12);
addCheck(new StrutsConfigControllerCheck(this, StrutsPreferences.INVALID_CONTROLLER),
"StrutsController11", "StrutsController12");
addCheck(new ResourceCheck(this, StrutsPreferences.INVALID_MESSAGE_RESOURCES),
"StrutsMessageResources11");
addCheck(new StrutsConfigCheck(this, StrutsPreferences.INVALID_INIT_PARAM),
ENT_STRUTSCONFIG + VER_SUFFIX_10, ENT_STRUTSCONFIG + VER_SUFFIX_11, ENT_STRUTSCONFIG + VER_SUFFIX_12);
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#getMarkerType()
*/
@Override
public String getMarkerType() {
return PROBLEM_TYPE;
}
public String getId() {
return ID;
}
public String getBuilderId() {
return null;
}
public IValidatingProjectTree getValidatingProjects(IProject project) {
IProjectValidationContext rootContext = contexts.get(project);
if(rootContext == null) {
rootContext = new ProjectValidationContext();
contexts.put(project, rootContext);
}
Set<IProject> projects = new HashSet<IProject>();
projects.add(project);
IValidatingProjectSet projectSet = new ValidatingProjectSet(project, projects, rootContext);
return new SimpleValidatingProjectTree(projectSet);
}
public boolean shouldValidate(IProject project) {
if(!project.isAccessible()) {
return false;
}
try {
return project.hasNature(StrutsProject.NATURE_ID);
} catch (CoreException e) {
WebModelPlugin.getDefault().logError(e);
}
return false;
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#init(org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.validation.IProjectValidationContext, org.eclipse.wst.validation.internal.provisional.core.IValidator, org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
@Override
public void init(IProject project, ContextValidationHelper validationHelper, IProjectValidationContext context, org.eclipse.wst.validation.internal.provisional.core.IValidator manager, IReporter reporter) {
super.init(project, validationHelper, context, manager, reporter);
projectName = project.getName();
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.validation.IValidator#validate(java.util.Set, org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.validation.IProjectValidationContext, org.jboss.tools.jst.web.kb.internal.validation.ValidatorManager, org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
public IStatus validate(Set<IFile> changedFiles, IProject project,
ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager,
IReporter reporter) throws ValidationException {
init(project, validationHelper, context, manager, reporter);
for (IFile file: changedFiles) {
if(file.getName().endsWith(XML_EXT)) {
XModelObject o = EclipseResourceUtil.createObjectForResource(file);
if(o != null && o.getModelEntity().getName().startsWith(ENT_STRUTSCONFIG)) {
validateStrutsConfigFile(o, file);
} else if(o != null && o.getModelEntity().getName().startsWith("FileWebApp")) {
validateWebXMLFile(o);
}
}
}
return OK_STATUS;
}
private void validateStrutsConfigFile(XModelObject object, IFile file) {
validateObject(object);
}
private void validateWebXMLFile(XModelObject object) {
XModelObject[] ss = WebAppHelper.getServlets(object);
for (XModelObject servlet: ss) {
for(XModelObject p: servlet.getChildren()) {
new CheckInitParam(this, StrutsPreferences.INVALID_INIT_PARAM).check(p);
}
}
}
private void validateObject(XModelObject object) {
String entity = object.getModelEntity().getName();
Set<Check> ch = checks.get(entity);
if(ch != null) {
for (Check c: ch) {
c.check(object);
}
}
XModelObject[] cs = object.getChildren();
for (XModelObject c: cs) {
validateObject(c);
}
}
/*
* (non-Javadoc)
* @see org.jboss.tools.jst.web.kb.validation.IValidator#validateAll(org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.validation.IProjectValidationContext, org.jboss.tools.jst.web.kb.internal.validation.ValidatorManager, org.eclipse.wst.validation.internal.provisional.core.IReporter)
*/
public IStatus validateAll(IProject project,
ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager,
IReporter reporter) throws ValidationException {
init(project, validationHelper, context, manager, reporter);
displaySubtask(StrutsValidatorMessages.VALIDATING_PROJECT, new String[]{projectName});
IPath webContentPath = WebUtils.getFirstWebContentPath(project);
+ if(webContentPath == null) {
+ return OK_STATUS;
+ }
IFolder webInf = null;
try {
// This code line never return null
webInf = project.getFolder(webContentPath.removeFirstSegments(1).append("WEB-INF")); //$NON-NLS-1$
// so never check it for null
if(webInf.isAccessible()) {
IResource[] rs = webInf.members();
// exception is not required here because if esbContent is not exist control
// never gets here
for (IResource r: rs) {
if(r instanceof IFile) {
IFile file = (IFile)r;
String name = file.getName();
if(name.endsWith(XML_EXT)) {
XModelObject o = EclipseResourceUtil.createObjectForResource(file);
if(o != null && o.getModelEntity().getName().startsWith(StrutsConstants.ENT_STRUTSCONFIG)) {
validateStrutsConfigFile(o, file);
}
}
}
}
}
} catch (CoreException e) {
// hiding exceptions is the evil so lets return EROOR Status with exception
return new Status(IStatus.ERROR,StrutsModelPlugin.PLUGIN_ID,MessageFormat.format("Validation error for project {0}",project.getLocation().toString()),e);
}
return OK_STATUS;
}
public boolean isEnabled(IProject project) {
return StrutsPreferences.isValidationEnabled(project);
}
@Override
protected String getPreferencePageId() {
return PREFERENCE_PAGE_ID;
}
}
| true | true | public IStatus validateAll(IProject project,
ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager,
IReporter reporter) throws ValidationException {
init(project, validationHelper, context, manager, reporter);
displaySubtask(StrutsValidatorMessages.VALIDATING_PROJECT, new String[]{projectName});
IPath webContentPath = WebUtils.getFirstWebContentPath(project);
IFolder webInf = null;
try {
// This code line never return null
webInf = project.getFolder(webContentPath.removeFirstSegments(1).append("WEB-INF")); //$NON-NLS-1$
// so never check it for null
if(webInf.isAccessible()) {
IResource[] rs = webInf.members();
// exception is not required here because if esbContent is not exist control
// never gets here
for (IResource r: rs) {
if(r instanceof IFile) {
IFile file = (IFile)r;
String name = file.getName();
if(name.endsWith(XML_EXT)) {
XModelObject o = EclipseResourceUtil.createObjectForResource(file);
if(o != null && o.getModelEntity().getName().startsWith(StrutsConstants.ENT_STRUTSCONFIG)) {
validateStrutsConfigFile(o, file);
}
}
}
}
}
} catch (CoreException e) {
// hiding exceptions is the evil so lets return EROOR Status with exception
return new Status(IStatus.ERROR,StrutsModelPlugin.PLUGIN_ID,MessageFormat.format("Validation error for project {0}",project.getLocation().toString()),e);
}
return OK_STATUS;
}
| public IStatus validateAll(IProject project,
ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager,
IReporter reporter) throws ValidationException {
init(project, validationHelper, context, manager, reporter);
displaySubtask(StrutsValidatorMessages.VALIDATING_PROJECT, new String[]{projectName});
IPath webContentPath = WebUtils.getFirstWebContentPath(project);
if(webContentPath == null) {
return OK_STATUS;
}
IFolder webInf = null;
try {
// This code line never return null
webInf = project.getFolder(webContentPath.removeFirstSegments(1).append("WEB-INF")); //$NON-NLS-1$
// so never check it for null
if(webInf.isAccessible()) {
IResource[] rs = webInf.members();
// exception is not required here because if esbContent is not exist control
// never gets here
for (IResource r: rs) {
if(r instanceof IFile) {
IFile file = (IFile)r;
String name = file.getName();
if(name.endsWith(XML_EXT)) {
XModelObject o = EclipseResourceUtil.createObjectForResource(file);
if(o != null && o.getModelEntity().getName().startsWith(StrutsConstants.ENT_STRUTSCONFIG)) {
validateStrutsConfigFile(o, file);
}
}
}
}
}
} catch (CoreException e) {
// hiding exceptions is the evil so lets return EROOR Status with exception
return new Status(IStatus.ERROR,StrutsModelPlugin.PLUGIN_ID,MessageFormat.format("Validation error for project {0}",project.getLocation().toString()),e);
}
return OK_STATUS;
}
|
diff --git a/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java b/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java
index 92439275..1ead23b5 100644
--- a/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java
+++ b/ProcessorCore/src/main/java/de/plushnikov/intellij/lombok/processor/clazz/log/AbstractLogProcessor.java
@@ -1,67 +1,72 @@
package de.plushnikov.intellij.lombok.processor.clazz.log;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.PsiType;
import com.intellij.psi.impl.light.LightElement;
import de.plushnikov.intellij.lombok.processor.clazz.AbstractLombokClassProcessor;
import de.plushnikov.intellij.lombok.psi.MyLightFieldBuilder;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Base lombok processor class for logger processing
*
* @author Plushnikov Michail
*/
public abstract class AbstractLogProcessor extends AbstractLombokClassProcessor {
private final static String loggerName = "log";
private final String loggerType;
private final String loggerInitializer;//TODO add Initializer support
protected AbstractLogProcessor(@NotNull String supportedAnnotation, @NotNull String loggerType, @NotNull String loggerInitializer) {
super(supportedAnnotation, PsiField.class);
this.loggerType = loggerType;
this.loggerInitializer = loggerInitializer;
}
public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
+ if (psiClass.isInterface() || psiClass.isAnnotationType()) {
+ //TODO create warning in code
+ //Logger Injection is not possible on interface or annotation types
+ return;
+ }
if (!hasFieldByName(psiClass, loggerName)) {
Project project = psiClass.getProject();
PsiManager manager = psiClass.getContainingFile().getManager();
PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass);
LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType)
.setHasInitializer(true)
.setContainingClass(psiClass)
- .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PUBLIC)
+ .setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PRIVATE)
.setNavigationElement(psiAnnotation);
target.add((Psi) loggerField);
} else {
//TODO create warning in code
//Not generating fieldName(): A field with that name already exists
}
}
protected boolean hasFieldByName(@NotNull PsiClass psiClass, String... fieldNames) {
final PsiField[] psiFields = collectClassFieldsIntern(psiClass);
for (PsiField psiField : psiFields) {
for (String fieldName : fieldNames) {
if (psiField.getName().equals(fieldName)) {
return true;
}
}
}
return false;
}
}
| false | true | public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
if (!hasFieldByName(psiClass, loggerName)) {
Project project = psiClass.getProject();
PsiManager manager = psiClass.getContainingFile().getManager();
PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass);
LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType)
.setHasInitializer(true)
.setContainingClass(psiClass)
.setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PUBLIC)
.setNavigationElement(psiAnnotation);
target.add((Psi) loggerField);
} else {
//TODO create warning in code
//Not generating fieldName(): A field with that name already exists
}
}
| public <Psi extends PsiElement> void process(@NotNull PsiClass psiClass, @NotNull PsiMethod[] classMethods, @NotNull PsiAnnotation psiAnnotation, @NotNull List<Psi> target) {
if (psiClass.isInterface() || psiClass.isAnnotationType()) {
//TODO create warning in code
//Logger Injection is not possible on interface or annotation types
return;
}
if (!hasFieldByName(psiClass, loggerName)) {
Project project = psiClass.getProject();
PsiManager manager = psiClass.getContainingFile().getManager();
PsiType psiLoggerType = JavaPsiFacade.getElementFactory(project).createTypeFromText(loggerType, psiClass);
LightElement loggerField = new MyLightFieldBuilder(manager, loggerName, psiLoggerType)
.setHasInitializer(true)
.setContainingClass(psiClass)
.setModifiers(PsiModifier.FINAL, PsiModifier.STATIC, PsiModifier.PRIVATE)
.setNavigationElement(psiAnnotation);
target.add((Psi) loggerField);
} else {
//TODO create warning in code
//Not generating fieldName(): A field with that name already exists
}
}
|
diff --git a/xfire-plexus/src/test/org/codehaus/xfire/plexus/config/ConfigurationTest.java b/xfire-plexus/src/test/org/codehaus/xfire/plexus/config/ConfigurationTest.java
index 16f3b3d7..5107e343 100644
--- a/xfire-plexus/src/test/org/codehaus/xfire/plexus/config/ConfigurationTest.java
+++ b/xfire-plexus/src/test/org/codehaus/xfire/plexus/config/ConfigurationTest.java
@@ -1,57 +1,57 @@
package org.codehaus.xfire.plexus.config;
import org.codehaus.xfire.plexus.PlexusXFireTest;
import org.codehaus.xfire.service.Service;
import org.jdom.Document;
/**
* @author <a href="mailto:[email protected]">Dan Diephouse</a>
* @since Sep 20, 2004
*/
public class ConfigurationTest
extends PlexusXFireTest
{
public void setUp()
throws Exception
{
System.setProperty("xfire.config", "/org/codehaus/xfire/plexus/config/services.xml");
super.setUp();
lookup(ConfigurationService.ROLE);
}
public void testRegister()
throws Exception
{
Service service = getServiceRegistry().getService("Echo");
assertNotNull(service);
assertNotNull(service.getInHandlers());
- assertEquals(3, service.getInHandlers().size());
+ assertEquals(4, service.getInHandlers().size());
assertNotNull(service.getOutHandlers());
assertEquals(2, service.getOutHandlers().size());
service = getServiceRegistry().getService("EchoXMLBeans");
assertNotNull(service);
assertTrue(getXFire().getInPhases().size() > 0);
// service = (ObjectService)
// getServiceRegistry().getService("EchoWSDL");
// assertNotNull( service );
// assertEquals(1, service.getOperations().size());
}
public void testInvoke()
throws Exception
{
Document response = invokeService("Echo", "/org/codehaus/xfire/plexus/config/echo11.xml");
addNamespace("e", "urn:Echo");
assertValid("//e:out[text()='Yo Yo']", response);
response = invokeService("EchoIntf", "/org/codehaus/xfire/plexus/config/echo11.xml");
addNamespace("e", "urn:Echo");
assertValid("//e:out[text()='Yo Yo']", response);
}
}
| true | true | public void testRegister()
throws Exception
{
Service service = getServiceRegistry().getService("Echo");
assertNotNull(service);
assertNotNull(service.getInHandlers());
assertEquals(3, service.getInHandlers().size());
assertNotNull(service.getOutHandlers());
assertEquals(2, service.getOutHandlers().size());
service = getServiceRegistry().getService("EchoXMLBeans");
assertNotNull(service);
assertTrue(getXFire().getInPhases().size() > 0);
// service = (ObjectService)
// getServiceRegistry().getService("EchoWSDL");
// assertNotNull( service );
// assertEquals(1, service.getOperations().size());
}
| public void testRegister()
throws Exception
{
Service service = getServiceRegistry().getService("Echo");
assertNotNull(service);
assertNotNull(service.getInHandlers());
assertEquals(4, service.getInHandlers().size());
assertNotNull(service.getOutHandlers());
assertEquals(2, service.getOutHandlers().size());
service = getServiceRegistry().getService("EchoXMLBeans");
assertNotNull(service);
assertTrue(getXFire().getInPhases().size() > 0);
// service = (ObjectService)
// getServiceRegistry().getService("EchoWSDL");
// assertNotNull( service );
// assertEquals(1, service.getOperations().size());
}
|
diff --git a/src/org/digitalcampus/oppia/task/SubmitTrackerMultipleTask.java b/src/org/digitalcampus/oppia/task/SubmitTrackerMultipleTask.java
index b4e40d4b..ac5c711a 100644
--- a/src/org/digitalcampus/oppia/task/SubmitTrackerMultipleTask.java
+++ b/src/org/digitalcampus/oppia/task/SubmitTrackerMultipleTask.java
@@ -1,206 +1,197 @@
package org.digitalcampus.oppia.task;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.digitalcampus.mobile.learning.R;
import org.digitalcampus.oppia.application.DbHelper;
import org.digitalcampus.oppia.application.MobileLearning;
import org.digitalcampus.oppia.model.TrackerLog;
import org.digitalcampus.oppia.utils.HTTPConnectionUtils;
import org.digitalcampus.oppia.utils.MetaDataUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.bugsense.trace.BugSenseHandler;
public class SubmitTrackerMultipleTask extends AsyncTask<Payload, Object, Payload> {
public final static String TAG = SubmitTrackerMultipleTask.class.getSimpleName();
private Context ctx;
private SharedPreferences prefs;
public SubmitTrackerMultipleTask(Context ctx) {
this.ctx = ctx;
prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
}
@Override
protected Payload doInBackground(Payload... params) {
DbHelper db = new DbHelper(ctx);
Payload payload = db.getUnsentLog();
db.close();
@SuppressWarnings("unchecked")
Collection<Collection<TrackerLog>> result = (Collection<Collection<TrackerLog>>) split((Collection<Object>) payload.getData(), MobileLearning.MAX_TRACKER_SUBMIT);
HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);
String url = HTTPConnectionUtils.createUrlWithCredentials(ctx, prefs, MobileLearning.TRACKER_PATH,true);
HttpPatch httpPatch = new HttpPatch(url);
for (Collection<TrackerLog> trackerBatch : result) {
String dataToSend = createDataString(trackerBatch);
try {
StringEntity se = new StringEntity(dataToSend);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPatch.setEntity(se);
//Log.d(TAG,url);
//Log.d(TAG,dataToSend);
// make request
HttpResponse response = client.execute(httpPatch);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096);
String responseStr = "";
String s = "";
while ((s = buffer.readLine()) != null) {
responseStr += s;
}
Log.d(TAG,responseStr);
switch (response.getStatusLine().getStatusCode()){
case 200: // submitted
DbHelper dbh = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh.markLogSubmitted(tl.getId());
}
dbh.close();
payload.setResult(true);
// update points
JSONObject jsonResp = new JSONObject(responseStr);
Editor editor = prefs.edit();
editor.putInt(ctx.getString(R.string.prefs_points), jsonResp.getInt("points"));
editor.putInt(ctx.getString(R.string.prefs_badges), jsonResp.getInt("badges"));
try {
editor.putBoolean(ctx.getString(R.string.prefs_scoring_enabled), jsonResp.getBoolean("scoring"));
} catch (JSONException e) {
e.printStackTrace();
}
editor.commit();
try {
JSONObject metadata = jsonResp.getJSONObject("metadata");
MetaDataUtils mu = new MetaDataUtils(ctx);
mu.saveMetaData(metadata, prefs);
} catch (JSONException e) {
e.printStackTrace();
}
break;
- // TODO remove this case statement when new server side released (v0.1.15)
- case 404: // submitted but invalid digest - returned 404 Not Found - so record as submitted so doesn't keep trying
- DbHelper dbh1 = new DbHelper(ctx);
- for(TrackerLog tl: trackerBatch){
- dbh1.markLogSubmitted(tl.getId());
- };
- dbh1.close();
- payload.setResult(true);
- break;
case 400: // submitted but invalid digest - returned 400 Bad Request - so record as submitted so doesn't keep trying
DbHelper dbh2 = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh2.markLogSubmitted(tl.getId());
};
dbh2.close();
payload.setResult(true);
break;
default:
payload.setResult(false);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
payload.setResult(false);
} catch (ClientProtocolException e) {
e.printStackTrace();
payload.setResult(false);
} catch (IOException e) {
e.printStackTrace();
payload.setResult(false);
} catch (JSONException e) {
BugSenseHandler.sendException(e);
e.printStackTrace();
payload.setResult(false);
}
}
return payload;
}
protected void onProgressUpdate(String... obj) {
// do nothing
}
@Override
protected void onPostExecute(Payload p) {
// reset submittask back to null after completion - so next call can run properly
MobileLearning app = (MobileLearning) ctx.getApplicationContext();
app.omSubmitTrackerMultipleTask = null;
}
private static Collection<Collection<TrackerLog>> split(Collection<Object> bigCollection, int maxBatchSize) {
Collection<Collection<TrackerLog>> result = new ArrayList<Collection<TrackerLog>>();
ArrayList<TrackerLog> currentBatch = null;
for (Object obj : bigCollection) {
TrackerLog tl = (TrackerLog) obj;
if (currentBatch == null) {
currentBatch = new ArrayList<TrackerLog>();
} else if (currentBatch.size() >= maxBatchSize) {
result.add(currentBatch);
currentBatch = new ArrayList<TrackerLog>();
}
currentBatch.add(tl);
}
if (currentBatch != null) {
result.add(currentBatch);
}
return result;
}
private String createDataString(Collection<TrackerLog> collection){
String s = "{\"objects\":[";
int counter = 0;
for(TrackerLog tl: collection){
counter++;
s += tl.getContent();
if(counter != collection.size()){
s += ",";
}
}
s += "]}";
return s;
}
}
| true | true | protected Payload doInBackground(Payload... params) {
DbHelper db = new DbHelper(ctx);
Payload payload = db.getUnsentLog();
db.close();
@SuppressWarnings("unchecked")
Collection<Collection<TrackerLog>> result = (Collection<Collection<TrackerLog>>) split((Collection<Object>) payload.getData(), MobileLearning.MAX_TRACKER_SUBMIT);
HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);
String url = HTTPConnectionUtils.createUrlWithCredentials(ctx, prefs, MobileLearning.TRACKER_PATH,true);
HttpPatch httpPatch = new HttpPatch(url);
for (Collection<TrackerLog> trackerBatch : result) {
String dataToSend = createDataString(trackerBatch);
try {
StringEntity se = new StringEntity(dataToSend);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPatch.setEntity(se);
//Log.d(TAG,url);
//Log.d(TAG,dataToSend);
// make request
HttpResponse response = client.execute(httpPatch);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096);
String responseStr = "";
String s = "";
while ((s = buffer.readLine()) != null) {
responseStr += s;
}
Log.d(TAG,responseStr);
switch (response.getStatusLine().getStatusCode()){
case 200: // submitted
DbHelper dbh = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh.markLogSubmitted(tl.getId());
}
dbh.close();
payload.setResult(true);
// update points
JSONObject jsonResp = new JSONObject(responseStr);
Editor editor = prefs.edit();
editor.putInt(ctx.getString(R.string.prefs_points), jsonResp.getInt("points"));
editor.putInt(ctx.getString(R.string.prefs_badges), jsonResp.getInt("badges"));
try {
editor.putBoolean(ctx.getString(R.string.prefs_scoring_enabled), jsonResp.getBoolean("scoring"));
} catch (JSONException e) {
e.printStackTrace();
}
editor.commit();
try {
JSONObject metadata = jsonResp.getJSONObject("metadata");
MetaDataUtils mu = new MetaDataUtils(ctx);
mu.saveMetaData(metadata, prefs);
} catch (JSONException e) {
e.printStackTrace();
}
break;
// TODO remove this case statement when new server side released (v0.1.15)
case 404: // submitted but invalid digest - returned 404 Not Found - so record as submitted so doesn't keep trying
DbHelper dbh1 = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh1.markLogSubmitted(tl.getId());
};
dbh1.close();
payload.setResult(true);
break;
case 400: // submitted but invalid digest - returned 400 Bad Request - so record as submitted so doesn't keep trying
DbHelper dbh2 = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh2.markLogSubmitted(tl.getId());
};
dbh2.close();
payload.setResult(true);
break;
default:
payload.setResult(false);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
payload.setResult(false);
} catch (ClientProtocolException e) {
e.printStackTrace();
payload.setResult(false);
} catch (IOException e) {
e.printStackTrace();
payload.setResult(false);
} catch (JSONException e) {
BugSenseHandler.sendException(e);
e.printStackTrace();
payload.setResult(false);
}
}
return payload;
}
| protected Payload doInBackground(Payload... params) {
DbHelper db = new DbHelper(ctx);
Payload payload = db.getUnsentLog();
db.close();
@SuppressWarnings("unchecked")
Collection<Collection<TrackerLog>> result = (Collection<Collection<TrackerLog>>) split((Collection<Object>) payload.getData(), MobileLearning.MAX_TRACKER_SUBMIT);
HTTPConnectionUtils client = new HTTPConnectionUtils(ctx);
String url = HTTPConnectionUtils.createUrlWithCredentials(ctx, prefs, MobileLearning.TRACKER_PATH,true);
HttpPatch httpPatch = new HttpPatch(url);
for (Collection<TrackerLog> trackerBatch : result) {
String dataToSend = createDataString(trackerBatch);
try {
StringEntity se = new StringEntity(dataToSend);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPatch.setEntity(se);
//Log.d(TAG,url);
//Log.d(TAG,dataToSend);
// make request
HttpResponse response = client.execute(httpPatch);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content), 4096);
String responseStr = "";
String s = "";
while ((s = buffer.readLine()) != null) {
responseStr += s;
}
Log.d(TAG,responseStr);
switch (response.getStatusLine().getStatusCode()){
case 200: // submitted
DbHelper dbh = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh.markLogSubmitted(tl.getId());
}
dbh.close();
payload.setResult(true);
// update points
JSONObject jsonResp = new JSONObject(responseStr);
Editor editor = prefs.edit();
editor.putInt(ctx.getString(R.string.prefs_points), jsonResp.getInt("points"));
editor.putInt(ctx.getString(R.string.prefs_badges), jsonResp.getInt("badges"));
try {
editor.putBoolean(ctx.getString(R.string.prefs_scoring_enabled), jsonResp.getBoolean("scoring"));
} catch (JSONException e) {
e.printStackTrace();
}
editor.commit();
try {
JSONObject metadata = jsonResp.getJSONObject("metadata");
MetaDataUtils mu = new MetaDataUtils(ctx);
mu.saveMetaData(metadata, prefs);
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 400: // submitted but invalid digest - returned 400 Bad Request - so record as submitted so doesn't keep trying
DbHelper dbh2 = new DbHelper(ctx);
for(TrackerLog tl: trackerBatch){
dbh2.markLogSubmitted(tl.getId());
};
dbh2.close();
payload.setResult(true);
break;
default:
payload.setResult(false);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
payload.setResult(false);
} catch (ClientProtocolException e) {
e.printStackTrace();
payload.setResult(false);
} catch (IOException e) {
e.printStackTrace();
payload.setResult(false);
} catch (JSONException e) {
BugSenseHandler.sendException(e);
e.printStackTrace();
payload.setResult(false);
}
}
return payload;
}
|
diff --git a/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java b/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
index 01498bb96..b5e7c60b1 100644
--- a/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
+++ b/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
@@ -1,63 +1,63 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is created by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.common.note;
import org.freeplane.core.extension.IExtension;
import org.freeplane.core.io.IElementContentHandler;
import org.freeplane.features.common.map.NodeModel;
import org.freeplane.features.common.text.NodeTextBuilder;
import org.freeplane.n3.nanoxml.XMLElement;
/**
* @author Dimitry Polivaev
*/
class NoteBuilder implements IElementContentHandler {
final private NoteController noteController;
public NoteBuilder(final NoteController noteController) {
super();
this.noteController = noteController;
}
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
return parent;
}
return null;
}
public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
final NoteModel note = new NoteModel();
- noteController.setStateIcon(((NodeModel) node), true);
note.setXml(xmlText);
((NodeModel) node).addExtension((IExtension) note);
+ noteController.setStateIcon(((NodeModel) node), true);
}
}
}
}
| false | true | public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
final NoteModel note = new NoteModel();
noteController.setStateIcon(((NodeModel) node), true);
note.setXml(xmlText);
((NodeModel) node).addExtension((IExtension) note);
}
}
}
| public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
final NoteModel note = new NoteModel();
note.setXml(xmlText);
((NodeModel) node).addExtension((IExtension) note);
noteController.setStateIcon(((NodeModel) node), true);
}
}
}
|
diff --git a/src/de/robv/android/xposed/mods/appsettings/hooks/Activities.java b/src/de/robv/android/xposed/mods/appsettings/hooks/Activities.java
index bcf8ed0..937e150 100644
--- a/src/de/robv/android/xposed/mods/appsettings/hooks/Activities.java
+++ b/src/de/robv/android/xposed/mods/appsettings/hooks/Activities.java
@@ -1,190 +1,190 @@
package de.robv.android.xposed.mods.appsettings.hooks;
import static de.robv.android.xposed.XposedBridge.hookMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findMethodExact;
import static de.robv.android.xposed.XposedHelpers.getAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.getObjectField;
import static de.robv.android.xposed.XposedHelpers.setAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.setIntField;
import java.lang.reflect.Method;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.mods.appsettings.Common;
import de.robv.android.xposed.mods.appsettings.XposedMod;
public class Activities {
private static final String PROP_FULLSCREEN = "AppSettings-Fullscreen";
private static final String PROP_KEEP_SCREEN_ON = "AppSettings-KeepScreenOn";
private static final String PROP_ORIENTATION = "AppSettings-Orientation";
public static void hookActivitySettings() {
try {
findAndHookMethod("com.android.internal.policy.impl.PhoneWindow", null, "generateLayout",
"com.android.internal.policy.impl.PhoneWindow.DecorView", new XC_MethodHook() {
@SuppressLint("InlinedApi")
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Window window = (Window) param.thisObject;
Context context = window.getContext();
String packageName = context.getPackageName();
if (!XposedMod.isActive(packageName))
return;
int fullscreen;
try {
fullscreen = XposedMod.prefs.getInt(packageName + Common.PREF_FULLSCREEN,
Common.FULLSCREEN_DEFAULT);
} catch (ClassCastException ex) {
// Legacy boolean setting
fullscreen = XposedMod.prefs.getBoolean(packageName + Common.PREF_FULLSCREEN, false)
? Common.FULLSCREEN_FORCE : Common.FULLSCREEN_DEFAULT;
}
if (fullscreen == Common.FULLSCREEN_FORCE) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
} else if (fullscreen == Common.FULLSCREEN_PREVENT) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.FALSE);
} else if (fullscreen == Common.FULLSCREEN_IMMERSIVE) {
if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_NO_TITLE, false))
window.requestFeature(Window.FEATURE_NO_TITLE);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_ALLOW_ON_LOCKSCREEN, false))
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_SCREEN_ON, false)) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setAdditionalInstanceField(window, PROP_KEEP_SCREEN_ON, Boolean.TRUE);
}
int orientation = XposedMod.prefs.getInt(packageName + Common.PREF_ORIENTATION, XposedMod.prefs.getInt(Common.PREF_DEFAULT + Common.PREF_ORIENTATION, 0));
if (orientation > 0 && orientation < Common.orientationCodes.length && context instanceof Activity) {
((Activity) context).setRequestedOrientation(Common.orientationCodes[orientation]);
setAdditionalInstanceField(context, PROP_ORIENTATION, orientation);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Window.class, "setFlags", int.class, int.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
int flags = (Integer) param.args[0];
int mask = (Integer) param.args[1];
if ((mask & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) {
Boolean fullscreen = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_FULLSCREEN);
if (fullscreen != null) {
if (fullscreen.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
param.args[0] = flags;
}
}
if ((mask & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0) {
Boolean keepScreenOn = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_KEEP_SCREEN_ON);
if (keepScreenOn != null) {
if (keepScreenOn.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
param.args[0] = flags;
}
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Activity.class, "setRequestedOrientation", int.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Integer orientation = (Integer) getAdditionalInstanceField(param.thisObject, PROP_ORIENTATION);
if (orientation != null)
- param.args[0] = orientation;
+ param.args[0] = Common.orientationCodes[orientation];
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
// Hook one of the several variations of ActivityStack.realStartActivityLocked from different ROMs
Method mthRealStartActivityLocked;
if (Build.VERSION.SDK_INT <= 18) {
try {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class, boolean.class);
} catch (NoSuchMethodError t) {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
} else {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStackSupervisor", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
hookMethod(mthRealStartActivityLocked, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String pkgName = (String) getObjectField(param.args[0], "packageName");
if (!XposedMod.isActive(pkgName, Common.PREF_RESIDENT))
return;
int adj = -12;
Object proc = getObjectField(param.args[0], "app");
// Override the *Adj values if meant to be resident in memory
if (proc != null) {
setIntField(proc, "maxAdj", adj);
if (Build.VERSION.SDK_INT <= 18)
setIntField(proc, "hiddenAdj", adj);
setIntField(proc, "curRawAdj", adj);
setIntField(proc, "setRawAdj", adj);
setIntField(proc, "curAdj", adj);
setIntField(proc, "setAdj", adj);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
}
}
| true | true | public static void hookActivitySettings() {
try {
findAndHookMethod("com.android.internal.policy.impl.PhoneWindow", null, "generateLayout",
"com.android.internal.policy.impl.PhoneWindow.DecorView", new XC_MethodHook() {
@SuppressLint("InlinedApi")
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Window window = (Window) param.thisObject;
Context context = window.getContext();
String packageName = context.getPackageName();
if (!XposedMod.isActive(packageName))
return;
int fullscreen;
try {
fullscreen = XposedMod.prefs.getInt(packageName + Common.PREF_FULLSCREEN,
Common.FULLSCREEN_DEFAULT);
} catch (ClassCastException ex) {
// Legacy boolean setting
fullscreen = XposedMod.prefs.getBoolean(packageName + Common.PREF_FULLSCREEN, false)
? Common.FULLSCREEN_FORCE : Common.FULLSCREEN_DEFAULT;
}
if (fullscreen == Common.FULLSCREEN_FORCE) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
} else if (fullscreen == Common.FULLSCREEN_PREVENT) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.FALSE);
} else if (fullscreen == Common.FULLSCREEN_IMMERSIVE) {
if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_NO_TITLE, false))
window.requestFeature(Window.FEATURE_NO_TITLE);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_ALLOW_ON_LOCKSCREEN, false))
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_SCREEN_ON, false)) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setAdditionalInstanceField(window, PROP_KEEP_SCREEN_ON, Boolean.TRUE);
}
int orientation = XposedMod.prefs.getInt(packageName + Common.PREF_ORIENTATION, XposedMod.prefs.getInt(Common.PREF_DEFAULT + Common.PREF_ORIENTATION, 0));
if (orientation > 0 && orientation < Common.orientationCodes.length && context instanceof Activity) {
((Activity) context).setRequestedOrientation(Common.orientationCodes[orientation]);
setAdditionalInstanceField(context, PROP_ORIENTATION, orientation);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Window.class, "setFlags", int.class, int.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
int flags = (Integer) param.args[0];
int mask = (Integer) param.args[1];
if ((mask & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) {
Boolean fullscreen = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_FULLSCREEN);
if (fullscreen != null) {
if (fullscreen.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
param.args[0] = flags;
}
}
if ((mask & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0) {
Boolean keepScreenOn = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_KEEP_SCREEN_ON);
if (keepScreenOn != null) {
if (keepScreenOn.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
param.args[0] = flags;
}
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Activity.class, "setRequestedOrientation", int.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Integer orientation = (Integer) getAdditionalInstanceField(param.thisObject, PROP_ORIENTATION);
if (orientation != null)
param.args[0] = orientation;
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
// Hook one of the several variations of ActivityStack.realStartActivityLocked from different ROMs
Method mthRealStartActivityLocked;
if (Build.VERSION.SDK_INT <= 18) {
try {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class, boolean.class);
} catch (NoSuchMethodError t) {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
} else {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStackSupervisor", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
hookMethod(mthRealStartActivityLocked, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String pkgName = (String) getObjectField(param.args[0], "packageName");
if (!XposedMod.isActive(pkgName, Common.PREF_RESIDENT))
return;
int adj = -12;
Object proc = getObjectField(param.args[0], "app");
// Override the *Adj values if meant to be resident in memory
if (proc != null) {
setIntField(proc, "maxAdj", adj);
if (Build.VERSION.SDK_INT <= 18)
setIntField(proc, "hiddenAdj", adj);
setIntField(proc, "curRawAdj", adj);
setIntField(proc, "setRawAdj", adj);
setIntField(proc, "curAdj", adj);
setIntField(proc, "setAdj", adj);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
}
| public static void hookActivitySettings() {
try {
findAndHookMethod("com.android.internal.policy.impl.PhoneWindow", null, "generateLayout",
"com.android.internal.policy.impl.PhoneWindow.DecorView", new XC_MethodHook() {
@SuppressLint("InlinedApi")
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Window window = (Window) param.thisObject;
Context context = window.getContext();
String packageName = context.getPackageName();
if (!XposedMod.isActive(packageName))
return;
int fullscreen;
try {
fullscreen = XposedMod.prefs.getInt(packageName + Common.PREF_FULLSCREEN,
Common.FULLSCREEN_DEFAULT);
} catch (ClassCastException ex) {
// Legacy boolean setting
fullscreen = XposedMod.prefs.getBoolean(packageName + Common.PREF_FULLSCREEN, false)
? Common.FULLSCREEN_FORCE : Common.FULLSCREEN_DEFAULT;
}
if (fullscreen == Common.FULLSCREEN_FORCE) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
} else if (fullscreen == Common.FULLSCREEN_PREVENT) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.FALSE);
} else if (fullscreen == Common.FULLSCREEN_IMMERSIVE) {
if (Build.VERSION.SDK_INT >= 19) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setAdditionalInstanceField(window, PROP_FULLSCREEN, Boolean.TRUE);
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_NO_TITLE, false))
window.requestFeature(Window.FEATURE_NO_TITLE);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_ALLOW_ON_LOCKSCREEN, false))
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
if (XposedMod.prefs.getBoolean(packageName + Common.PREF_SCREEN_ON, false)) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setAdditionalInstanceField(window, PROP_KEEP_SCREEN_ON, Boolean.TRUE);
}
int orientation = XposedMod.prefs.getInt(packageName + Common.PREF_ORIENTATION, XposedMod.prefs.getInt(Common.PREF_DEFAULT + Common.PREF_ORIENTATION, 0));
if (orientation > 0 && orientation < Common.orientationCodes.length && context instanceof Activity) {
((Activity) context).setRequestedOrientation(Common.orientationCodes[orientation]);
setAdditionalInstanceField(context, PROP_ORIENTATION, orientation);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Window.class, "setFlags", int.class, int.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
int flags = (Integer) param.args[0];
int mask = (Integer) param.args[1];
if ((mask & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) {
Boolean fullscreen = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_FULLSCREEN);
if (fullscreen != null) {
if (fullscreen.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
param.args[0] = flags;
}
}
if ((mask & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0) {
Boolean keepScreenOn = (Boolean) getAdditionalInstanceField(param.thisObject, PROP_KEEP_SCREEN_ON);
if (keepScreenOn != null) {
if (keepScreenOn.booleanValue()) {
flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
param.args[0] = flags;
}
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
findAndHookMethod(Activity.class, "setRequestedOrientation", int.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Integer orientation = (Integer) getAdditionalInstanceField(param.thisObject, PROP_ORIENTATION);
if (orientation != null)
param.args[0] = Common.orientationCodes[orientation];
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
try {
// Hook one of the several variations of ActivityStack.realStartActivityLocked from different ROMs
Method mthRealStartActivityLocked;
if (Build.VERSION.SDK_INT <= 18) {
try {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class, boolean.class);
} catch (NoSuchMethodError t) {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStack", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
} else {
mthRealStartActivityLocked = findMethodExact("com.android.server.am.ActivityStackSupervisor", null, "realStartActivityLocked",
"com.android.server.am.ActivityRecord", "com.android.server.am.ProcessRecord",
boolean.class, boolean.class);
}
hookMethod(mthRealStartActivityLocked, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
String pkgName = (String) getObjectField(param.args[0], "packageName");
if (!XposedMod.isActive(pkgName, Common.PREF_RESIDENT))
return;
int adj = -12;
Object proc = getObjectField(param.args[0], "app");
// Override the *Adj values if meant to be resident in memory
if (proc != null) {
setIntField(proc, "maxAdj", adj);
if (Build.VERSION.SDK_INT <= 18)
setIntField(proc, "hiddenAdj", adj);
setIntField(proc, "curRawAdj", adj);
setIntField(proc, "setRawAdj", adj);
setIntField(proc, "curAdj", adj);
setIntField(proc, "setAdj", adj);
}
}
});
} catch (Throwable e) {
XposedBridge.log(e);
}
}
|
diff --git a/TarsosDSP/src/main/java/be/hogent/tarsos/dsp/AudioEvent.java b/TarsosDSP/src/main/java/be/hogent/tarsos/dsp/AudioEvent.java
index a16d4d6..d8c2282 100644
--- a/TarsosDSP/src/main/java/be/hogent/tarsos/dsp/AudioEvent.java
+++ b/TarsosDSP/src/main/java/be/hogent/tarsos/dsp/AudioEvent.java
@@ -1,223 +1,223 @@
/*
* _______ _____ _____ _____
* |__ __| | __ \ / ____| __ \
* | | __ _ _ __ ___ ___ ___| | | | (___ | |__) |
* | |/ _` | '__/ __|/ _ \/ __| | | |\___ \| ___/
* | | (_| | | \__ \ (_) \__ \ |__| |____) | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_|
*
* -----------------------------------------------------------
*
* TarsosDSP is developed by Joren Six at
* The School of Arts,
* University College Ghent,
* Hoogpoort 64, 9000 Ghent - Belgium
*
* -----------------------------------------------------------
*
* Info: http://tarsos.0110.be/tag/TarsosDSP
* Github: https://github.com/JorenSix/TarsosDSP
* Releases: http://tarsos.0110.be/releases/TarsosDSP/
*
* TarsosDSP includes modified source code by various authors,
* for credits and info, see README.
*
*/
package be.hogent.tarsos.dsp;
import java.util.Arrays;
import javax.sound.sampled.AudioFormat;
import be.hogent.tarsos.dsp.util.AudioFloatConverter;
/**
* An audio event flows through the processing pipeline. The object is reused for performance reasons.
* The arrays with audio information are also reused, so watch out when using the buffer getter and setters.
*
* @author Joren Six
*/
public class AudioEvent {
/**
* The format specifies a particular arrangement of data in a sound stream.
*/
private final AudioFormat format;
private final AudioFloatConverter converter;
/**
* The audio data encoded in floats from -1.0 to 1.0.
*/
private float[] floatBuffer;
/**
* The audio data encoded in bytes according to format.
*/
private byte[] byteBuffer;
/**
* The overlap in samples.
*/
private int overlap;
/**
* The length of the stream, expressed in sample frames rather than bytes
*/
private long frameLength;
/**
* The number of bytes processed before this event. It can be used to calculate the time stamp for when this event started.
*/
private long bytesProcessed;
public AudioEvent(AudioFormat format,long frameLength){
this.format = format;
this.converter = AudioFloatConverter.getConverter(format);
this.overlap = 0;
this.frameLength = frameLength;
}
public float getSampleRate(){
return format.getSampleRate();
}
public int getBufferSize(){
return getFloatBuffer().length;
}
public int getOverlap(){
return overlap;
}
public void setOverlap(int newOverlap){
overlap = newOverlap;
}
public void setBytesProcessed(long bytesProcessed){
this.bytesProcessed = bytesProcessed;
}
/**
* Calculates and returns the time stamp at the beginning of this audio event.
* @return The time stamp at the beginning of the event in seconds.
*/
public double getTimeStamp(){
return bytesProcessed / format.getFrameSize() / format.getSampleRate();
}
public long getSamplesProcessed(){
return bytesProcessed / format.getFrameSize();
}
/**
* Calculate the progress in percentage of the total number of frames.
*
* @return a percentage of processed frames or a negative number if the
* number of frames is not known beforehand.
*/
public double getProgress(){
return bytesProcessed / format.getFrameSize() / (double) frameLength;
}
/**
* Return a byte array with the audio data in bytes.
* A conversion is done from float, cache accordingly on the other side...
*
* @return a byte array with the audio data in bytes.
*/
public byte[] getByteBuffer(){
int length = getFloatBuffer().length * format.getFrameSize();
if(byteBuffer == null || byteBuffer.length != length){
byteBuffer = new byte[length];
}
converter.toByteArray(getFloatBuffer(), byteBuffer);
return byteBuffer;
}
public void setFloatBuffer(float[] floatBuffer) {
this.floatBuffer = floatBuffer;
}
public float[] getFloatBuffer(){
return floatBuffer;
}
/**
* Calculates and returns the root mean square of the signal. Please
* cache the result since it is calculated every time.
* @return The <a
* href="http://en.wikipedia.org/wiki/Root_mean_square">RMS</a> of
* the signal present in the current buffer.
*/
public double getRMS() {
return calculateRMS(floatBuffer);
}
/**
* Calculates and returns the root mean square of the signal. Please
* cache the result since it is calculated every time.
* @param floatBuffer The audio buffer to calculate the RMS for.
* @return The <a
* href="http://en.wikipedia.org/wiki/Root_mean_square">RMS</a> of
* the signal present in the current buffer.
*/
public static double calculateRMS(float[] floatBuffer){
double rms = 0.0;
for (int i = 0; i < floatBuffer.length; i++) {
- rms =+ floatBuffer[i] * floatBuffer[i];
+ rms += floatBuffer[i] * floatBuffer[i];
}
rms = rms / Double.valueOf(floatBuffer.length);
rms = Math.sqrt(rms);
return rms;
}
public void clearFloatBuffer() {
Arrays.fill(floatBuffer, 0);
}
/**
* Returns the dBSPL for a buffer.
*
* @param buffer
* The buffer with audio information.
* @return The dBSPL level for the buffer.
*/
private double soundPressureLevel(final float[] buffer) {
double value = Math.pow(localEnergy(buffer), 0.5);
value = value / buffer.length;
return linearToDecibel(value);
}
/**
* Calculates the local (linear) energy of an audio buffer.
*
* @param buffer
* The audio buffer.
* @return The local (linear) energy of an audio buffer.
*/
private double localEnergy(final float[] buffer) {
double power = 0.0D;
for (float element : buffer) {
power += element * element;
}
return power;
}
/**
* Converts a linear to a dB value.
*
* @param value
* The value to convert.
* @return The converted value.
*/
private double linearToDecibel(final double value) {
return 20.0 * Math.log10(value);
}
public boolean isSilence(double silenceThreshold) {
return soundPressureLevel(floatBuffer) < silenceThreshold;
}
}
| true | true | public static double calculateRMS(float[] floatBuffer){
double rms = 0.0;
for (int i = 0; i < floatBuffer.length; i++) {
rms =+ floatBuffer[i] * floatBuffer[i];
}
rms = rms / Double.valueOf(floatBuffer.length);
rms = Math.sqrt(rms);
return rms;
}
| public static double calculateRMS(float[] floatBuffer){
double rms = 0.0;
for (int i = 0; i < floatBuffer.length; i++) {
rms += floatBuffer[i] * floatBuffer[i];
}
rms = rms / Double.valueOf(floatBuffer.length);
rms = Math.sqrt(rms);
return rms;
}
|
diff --git a/aop/src/main/org/jboss/aop/advice/AbstractAdvice.java b/aop/src/main/org/jboss/aop/advice/AbstractAdvice.java
index dd56b1ee..2086290f 100644
--- a/aop/src/main/org/jboss/aop/advice/AbstractAdvice.java
+++ b/aop/src/main/org/jboss/aop/advice/AbstractAdvice.java
@@ -1,320 +1,320 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* 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.jboss.aop.advice;
import org.jboss.aop.instrument.Untransformable;
import org.jboss.aop.joinpoint.ConstructionInvocation;
import org.jboss.aop.joinpoint.ConstructorCalledByConstructorInvocation;
import org.jboss.aop.joinpoint.ConstructorCalledByMethodInvocation;
import org.jboss.aop.joinpoint.ConstructorInvocation;
import org.jboss.aop.joinpoint.FieldInvocation;
import org.jboss.aop.joinpoint.FieldReadInvocation;
import org.jboss.aop.joinpoint.FieldWriteInvocation;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodCalledByConstructorInvocation;
import org.jboss.aop.joinpoint.MethodCalledByMethodInvocation;
import org.jboss.aop.joinpoint.MethodInvocation;
import java.lang.reflect.Method;
/**
* Comment
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision$
*/
public abstract class AbstractAdvice implements Interceptor, Untransformable
{
private static final Class[] INVOCATION_SIGNATURE = {Invocation.class};
private static final Class[] METHOD_SIGNATURE = {MethodInvocation.class};
private static final Class[] CONSTRUCTOR_SIGNATURE = {ConstructorInvocation.class};
private static final Class[] CONSTRUCTION_SIGNATURE = {ConstructionInvocation.class};
private static final Class[] FIELD_SIGNATURE = {FieldInvocation.class};
private static final Class[] FIELD_READ_SIGNATURE = {FieldReadInvocation.class};
private static final Class[] FIELD_WRITE_SIGNATURE = {FieldWriteInvocation.class};
private static final Class[] METHOD_CALLED_BY_METHOD_SIGNATURE = {MethodCalledByMethodInvocation.class};
private static final Class[] METHOD_CALLED_BY_CONSTRUCTOR_SIGNATURE = {MethodCalledByConstructorInvocation.class};
private static final Class[] CON_CALLED_BY_METHOD_SIGNATURE = {ConstructorCalledByMethodInvocation.class};
private static final Class[] CON_CALLED_BY_CONSTRUCTOR_SIGNATURE = {ConstructorCalledByConstructorInvocation.class};
protected Method invocationAdvice;
protected Method methodAdvice;
protected Method constructorAdvice;
protected Method constructionAdvice;
protected Method fieldAdvice;
protected Method fieldReadAdvice;
protected Method fieldWriteAdvice;
protected Method methodCalledByMethodAdvice;
protected Method methodCalledByConstructorAdvice;
protected Method conCalledByMethodAdvice;
protected Method conCalledByConstructorAdvice;
protected Class aspectClass;
protected String adviceName;
protected void init(String advice, Class aspectClass)
{
this.aspectClass = aspectClass;
this.adviceName = advice;
invocationAdvice = findByInvocation(adviceName, aspectClass);
if (invocationAdvice == null)
{
methodAdvice = findByMethodInvocation(adviceName, aspectClass);
constructorAdvice = findByConstructorInvocation(adviceName, aspectClass);
constructionAdvice = findByConstructionInvocation(adviceName, aspectClass);
fieldAdvice = findByFieldInvocation(adviceName, aspectClass);
if (fieldAdvice == null)
{
fieldReadAdvice = findByFieldReadInvocation(adviceName, aspectClass);
fieldWriteAdvice = findByFieldWriteInvocation(adviceName, aspectClass);
}
methodCalledByMethodAdvice = findByMethodCalledByMethodInvocation(adviceName, aspectClass);
methodCalledByConstructorAdvice = findByMethodCalledByConstructorInvocation(adviceName, aspectClass);
conCalledByMethodAdvice = findByConstructorCalledByMethodInvocation(adviceName, aspectClass);
conCalledByConstructorAdvice = findByConstructorCalledByConstructorInvocation(adviceName, aspectClass);
}
}
protected static Method findByInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, INVOCATION_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByMethodInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, METHOD_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByFieldInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, FIELD_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByFieldReadInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, FIELD_READ_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByFieldWriteInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, FIELD_WRITE_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByConstructorInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, CONSTRUCTOR_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByConstructionInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, CONSTRUCTION_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByMethodCalledByMethodInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, METHOD_CALLED_BY_METHOD_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByMethodCalledByConstructorInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, METHOD_CALLED_BY_CONSTRUCTOR_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByConstructorCalledByMethodInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, CON_CALLED_BY_METHOD_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected static Method findByConstructorCalledByConstructorInvocation(String adviceName, Class clazz)
{
try
{
return clazz.getMethod(adviceName, CON_CALLED_BY_CONSTRUCTOR_SIGNATURE);
}
catch (NoSuchMethodException e)
{
// complete
}
return null;
}
protected Method resolveAdvice(Invocation invocation)
{
if (invocationAdvice != null) return invocationAdvice;
if (invocation instanceof MethodInvocation)
{
if (methodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodInvocation advice " + getName());
}
return methodAdvice;
}
if (invocation instanceof FieldInvocation)
{
if (fieldAdvice != null) return fieldAdvice;
if (invocation instanceof FieldReadInvocation)
{
if (fieldReadAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldReadInvocation advice " + getName());
}
return fieldReadAdvice;
}
if (invocation instanceof FieldWriteInvocation)
{
if (fieldWriteAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldWriteInvocation advice " + getName());
}
return fieldWriteAdvice;
}
}
if (invocation instanceof ConstructorInvocation)
{
if (constructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorInvocation advice " + getName());
}
return constructorAdvice;
}
if (invocation instanceof ConstructionInvocation)
{
- if (constructorAdvice == null)
+ if (constructionAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructionInvocation advice " + getName());
}
- return constructorAdvice;
+ return constructionAdvice;
}
if (invocation instanceof MethodCalledByMethodInvocation)
{
if (methodCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByMethodInvocation advice " + getName());
}
return methodCalledByMethodAdvice;
}
if (invocation instanceof MethodCalledByConstructorInvocation)
{
if (methodCalledByConstructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByConstructorInvocation advice " + getName());
}
return methodCalledByConstructorAdvice;
}
if (invocation instanceof ConstructorCalledByMethodInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByMethodInvocation advice " + getName());
}
return conCalledByMethodAdvice;
}
if (invocation instanceof ConstructorCalledByConstructorInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByConstructorInvocation advice " + getName());
}
return conCalledByConstructorAdvice;
}
throw new RuntimeException("Should Be Unreachable, but unable to discover Advice");
}
}
| false | true | protected Method resolveAdvice(Invocation invocation)
{
if (invocationAdvice != null) return invocationAdvice;
if (invocation instanceof MethodInvocation)
{
if (methodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodInvocation advice " + getName());
}
return methodAdvice;
}
if (invocation instanceof FieldInvocation)
{
if (fieldAdvice != null) return fieldAdvice;
if (invocation instanceof FieldReadInvocation)
{
if (fieldReadAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldReadInvocation advice " + getName());
}
return fieldReadAdvice;
}
if (invocation instanceof FieldWriteInvocation)
{
if (fieldWriteAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldWriteInvocation advice " + getName());
}
return fieldWriteAdvice;
}
}
if (invocation instanceof ConstructorInvocation)
{
if (constructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorInvocation advice " + getName());
}
return constructorAdvice;
}
if (invocation instanceof ConstructionInvocation)
{
if (constructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructionInvocation advice " + getName());
}
return constructorAdvice;
}
if (invocation instanceof MethodCalledByMethodInvocation)
{
if (methodCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByMethodInvocation advice " + getName());
}
return methodCalledByMethodAdvice;
}
if (invocation instanceof MethodCalledByConstructorInvocation)
{
if (methodCalledByConstructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByConstructorInvocation advice " + getName());
}
return methodCalledByConstructorAdvice;
}
if (invocation instanceof ConstructorCalledByMethodInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByMethodInvocation advice " + getName());
}
return conCalledByMethodAdvice;
}
if (invocation instanceof ConstructorCalledByConstructorInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByConstructorInvocation advice " + getName());
}
return conCalledByConstructorAdvice;
}
throw new RuntimeException("Should Be Unreachable, but unable to discover Advice");
}
| protected Method resolveAdvice(Invocation invocation)
{
if (invocationAdvice != null) return invocationAdvice;
if (invocation instanceof MethodInvocation)
{
if (methodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodInvocation advice " + getName());
}
return methodAdvice;
}
if (invocation instanceof FieldInvocation)
{
if (fieldAdvice != null) return fieldAdvice;
if (invocation instanceof FieldReadInvocation)
{
if (fieldReadAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldReadInvocation advice " + getName());
}
return fieldReadAdvice;
}
if (invocation instanceof FieldWriteInvocation)
{
if (fieldWriteAdvice == null)
{
throw new IllegalStateException("Unable to resolve FieldWriteInvocation advice " + getName());
}
return fieldWriteAdvice;
}
}
if (invocation instanceof ConstructorInvocation)
{
if (constructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorInvocation advice " + getName());
}
return constructorAdvice;
}
if (invocation instanceof ConstructionInvocation)
{
if (constructionAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructionInvocation advice " + getName());
}
return constructionAdvice;
}
if (invocation instanceof MethodCalledByMethodInvocation)
{
if (methodCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByMethodInvocation advice " + getName());
}
return methodCalledByMethodAdvice;
}
if (invocation instanceof MethodCalledByConstructorInvocation)
{
if (methodCalledByConstructorAdvice == null)
{
throw new IllegalStateException("Unable to resolve MethodCalledByConstructorInvocation advice " + getName());
}
return methodCalledByConstructorAdvice;
}
if (invocation instanceof ConstructorCalledByMethodInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByMethodInvocation advice " + getName());
}
return conCalledByMethodAdvice;
}
if (invocation instanceof ConstructorCalledByConstructorInvocation)
{
if (conCalledByMethodAdvice == null)
{
throw new IllegalStateException("Unable to resolve ConstructorCalledByConstructorInvocation advice " + getName());
}
return conCalledByConstructorAdvice;
}
throw new RuntimeException("Should Be Unreachable, but unable to discover Advice");
}
|
diff --git a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/Replicate.java b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/Replicate.java
index bc4e0bba1..d56d1cdcd 100644
--- a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/Replicate.java
+++ b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/Replicate.java
@@ -1,97 +1,97 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.sshd.commands;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.PushAllProjectsOp;
import com.google.gerrit.server.git.ReplicationQueue;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.sshd.BaseCommand;
import com.google.inject.Inject;
import org.apache.sshd.server.Environment;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/** Force a project to replicate, again. */
final class Replicate extends BaseCommand {
@Option(name = "--all", usage = "push all known projects")
private boolean all;
@Option(name = "--url", metaVar = "PATTERN", usage = "pattern to match URL on")
private String urlMatch;
@Argument(index = 0, multiValued = true, metaVar = "PROJECT", usage = "project name")
private List<String> projectNames = new ArrayList<String>(2);
@Inject
IdentifiedUser currentUser;
@Inject
private PushAllProjectsOp.Factory pushAllOpFactory;
@Inject
private ReplicationQueue replication;
@Inject
private ProjectCache projectCache;
@Override
public void start(final Environment env) {
startThread(new CommandRunnable() {
@Override
public void run() throws Exception {
if (!currentUser.getCapabilities().canStartReplication()) {
String msg = String.format(
"fatal: %s does not have \"Start Replication\" capability.",
currentUser.getUserName());
throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg);
}
parseCommandLine();
Replicate.this.schedule();
}
});
}
private void schedule() throws Failure {
if (all && projectNames.size() > 0) {
- throw new Failure(1, "error: cannot combine --all and PROJECT");
+ throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT");
}
if (!replication.isEnabled()) {
throw new Failure(1, "error: replication not enabled");
}
if (all) {
pushAllOpFactory.create(urlMatch).start(0, TimeUnit.SECONDS);
} else {
for (final String name : projectNames) {
final Project.NameKey key = new Project.NameKey(name);
if (projectCache.get(key) != null) {
replication.scheduleFullSync(key, urlMatch);
} else {
- throw new Failure(1, "error: '" + name + "': not a Gerrit project");
+ throw new UnloggedFailure(1, "error: '" + name + "': not a Gerrit project");
}
}
}
}
}
| false | true | private void schedule() throws Failure {
if (all && projectNames.size() > 0) {
throw new Failure(1, "error: cannot combine --all and PROJECT");
}
if (!replication.isEnabled()) {
throw new Failure(1, "error: replication not enabled");
}
if (all) {
pushAllOpFactory.create(urlMatch).start(0, TimeUnit.SECONDS);
} else {
for (final String name : projectNames) {
final Project.NameKey key = new Project.NameKey(name);
if (projectCache.get(key) != null) {
replication.scheduleFullSync(key, urlMatch);
} else {
throw new Failure(1, "error: '" + name + "': not a Gerrit project");
}
}
}
}
| private void schedule() throws Failure {
if (all && projectNames.size() > 0) {
throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT");
}
if (!replication.isEnabled()) {
throw new Failure(1, "error: replication not enabled");
}
if (all) {
pushAllOpFactory.create(urlMatch).start(0, TimeUnit.SECONDS);
} else {
for (final String name : projectNames) {
final Project.NameKey key = new Project.NameKey(name);
if (projectCache.get(key) != null) {
replication.scheduleFullSync(key, urlMatch);
} else {
throw new UnloggedFailure(1, "error: '" + name + "': not a Gerrit project");
}
}
}
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/list.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/list.java
index b9b5827..22ff34c 100644
--- a/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/list.java
+++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/list.java
@@ -1,183 +1,183 @@
package nl.giantit.minecraft.GiantShop.core.Commands.Chat;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.Misc.Heraut;
import nl.giantit.minecraft.GiantShop.Misc.Messages;
import nl.giantit.minecraft.GiantShop.Misc.Misc;
import nl.giantit.minecraft.GiantShop.core.config;
import nl.giantit.minecraft.GiantShop.core.Database.Database;
import nl.giantit.minecraft.GiantShop.core.Database.drivers.iDriver;
import nl.giantit.minecraft.GiantShop.core.Items.Items;
import nl.giantit.minecraft.GiantShop.core.Tools.Discount.Discounter;
import nl.giantit.minecraft.GiantShop.core.perms.Permission;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* @author Giant
*/
public class list {
public static void list(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
Permission perms = GiantShop.getPlugin().getPermHandler().getEngine();
config conf = config.Obtain();
Discounter disc = GiantShop.getPlugin().getDiscounter();
if(perms.has(player, "giantshop.shop.list")) {
String name = GiantShop.getPlugin().getPubName();
int perPage = conf.getInt("GiantShop.global.perPage");
int curPag = 0;
if(args.length >= 2) {
try{
curPag = Integer.parseInt(args[1]);
}catch(NumberFormatException e) {
curPag = 1;
}
}else
curPag = 1;
curPag = (curPag > 0) ? curPag : 1;
iDriver DB = Database.Obtain().getEngine();
ArrayList<String> fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> t = new HashMap<String, String>();
if(conf.getBoolean("GiantShop.stock.hideEmptyStock")) {
t.put("kind", "NOT");
t.put("data", "0");
where.put("stock", t);
}
HashMap<String, String> order = new HashMap<String, String>();
order.put("itemID", "ASC");
order.put("type", "ASC");
ArrayList<HashMap<String, String>> data = DB.select(fields).from("#__items").where(where, true).orderBy(order).execQuery();
int pages = ((int)Math.ceil((double)data.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)data.size() / (double)perPage);
int start = (curPag * perPage) - perPage;
if(data.size() <= 0) {
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noItems"));
}else if(curPag > pages) {
Heraut.say(player, "&e[&3" + name + "&e]&c My Item list only has &e" + pages + " &cpages!!");
}else{
Heraut.say(player, "&e[&3" + name + "&e]&f Item list. Page: &e" + curPag + "&f/&e" + pages);
for(int i = start; i < (((start + perPage) > data.size()) ? data.size() : (start + perPage)); i++) {
HashMap<String, String> entry = data.get(i);
int stock = Integer.parseInt(entry.get("stock"));
int maxStock = Integer.parseInt(entry.get("maxstock"));
double sellFor = Double.parseDouble(entry.get("sellfor"));
double buyFor = Double.parseDouble(entry.get("buyfor"));
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) {
if(buyFor != -1)
buyFor = buyFor * (1.0 - maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 - maxDefl / 100.0);
}else if(stock <= atmi) {
if(buyFor != -1)
buyFor = buyFor * (1.0 + maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 + maxDefl / 100.0);
}else{
if(stock < split) {
if(buyFor != -1)
buyFor = (double)Math.round((buyFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = (double)Math.round((sellFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
}else if(stock > split) {
if(buyFor != -1)
buyFor = 2.0 + (double)Math.round((buyFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = 2.0 + (double)Math.round((sellFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
}
}
}
Integer type = Integer.parseInt(entry.get("type"));
type = type <= 0 ? null : type;
int discount = disc.getDiscount(iH.getItemIDByName(iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type)), player);
if(discount > 0) {
double actualDiscount = (100 - discount) / 100D;
buyFor = Misc.Round(buyFor * actualDiscount, 2);
if(conf.getBoolean(GiantShop.getPlugin().getName() + ".discounts.affectsSales"))
sellFor = Misc.Round(sellFor * actualDiscount, 2);
}
String sf = String.valueOf(sellFor);
String bf = String.valueOf(buyFor);
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", entry.get("itemid"));
params.put("type", (!entry.get("type").equals("-1") ? entry.get("type") : "0"));
params.put("name", iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type));
params.put("perStack", entry.get("perstack"));
- params.put("sellFor", (!sf.equals("-1.0") ? sf : "Not for sale!"));
- params.put("buyFor", (!bf.equals("-1.0") ? bf : "No returns!"));
+ params.put("sellFor", (!sf.equals("-1.0") && !sf.equals("-1") ? sf : "Not for sale!"));
+ params.put("buyFor", (!bf.equals("-1.0") && !sf.equals("-1") ? bf : "No returns!"));
if(conf.getBoolean("GiantShop.stock.useStock") == true) {
params.put("stock", (!entry.get("stock").equals("-1") ? entry.get("stock") : "unlimited"));
params.put("maxStock", (!entry.get("maxstock").equals("-1") ? entry.get("maxstock") : "unlimited"));
}else{
params.put("stock", "unlimited");
params.put("maxStock", "unlimited");
}
// Future stuff
// Probably am going to want to do this VERY different though :D
/* if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(entry.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
* break;
* }
* }
* }else
*/
Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "list");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
}
| true | true | public static void list(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
Permission perms = GiantShop.getPlugin().getPermHandler().getEngine();
config conf = config.Obtain();
Discounter disc = GiantShop.getPlugin().getDiscounter();
if(perms.has(player, "giantshop.shop.list")) {
String name = GiantShop.getPlugin().getPubName();
int perPage = conf.getInt("GiantShop.global.perPage");
int curPag = 0;
if(args.length >= 2) {
try{
curPag = Integer.parseInt(args[1]);
}catch(NumberFormatException e) {
curPag = 1;
}
}else
curPag = 1;
curPag = (curPag > 0) ? curPag : 1;
iDriver DB = Database.Obtain().getEngine();
ArrayList<String> fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> t = new HashMap<String, String>();
if(conf.getBoolean("GiantShop.stock.hideEmptyStock")) {
t.put("kind", "NOT");
t.put("data", "0");
where.put("stock", t);
}
HashMap<String, String> order = new HashMap<String, String>();
order.put("itemID", "ASC");
order.put("type", "ASC");
ArrayList<HashMap<String, String>> data = DB.select(fields).from("#__items").where(where, true).orderBy(order).execQuery();
int pages = ((int)Math.ceil((double)data.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)data.size() / (double)perPage);
int start = (curPag * perPage) - perPage;
if(data.size() <= 0) {
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noItems"));
}else if(curPag > pages) {
Heraut.say(player, "&e[&3" + name + "&e]&c My Item list only has &e" + pages + " &cpages!!");
}else{
Heraut.say(player, "&e[&3" + name + "&e]&f Item list. Page: &e" + curPag + "&f/&e" + pages);
for(int i = start; i < (((start + perPage) > data.size()) ? data.size() : (start + perPage)); i++) {
HashMap<String, String> entry = data.get(i);
int stock = Integer.parseInt(entry.get("stock"));
int maxStock = Integer.parseInt(entry.get("maxstock"));
double sellFor = Double.parseDouble(entry.get("sellfor"));
double buyFor = Double.parseDouble(entry.get("buyfor"));
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) {
if(buyFor != -1)
buyFor = buyFor * (1.0 - maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 - maxDefl / 100.0);
}else if(stock <= atmi) {
if(buyFor != -1)
buyFor = buyFor * (1.0 + maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 + maxDefl / 100.0);
}else{
if(stock < split) {
if(buyFor != -1)
buyFor = (double)Math.round((buyFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = (double)Math.round((sellFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
}else if(stock > split) {
if(buyFor != -1)
buyFor = 2.0 + (double)Math.round((buyFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = 2.0 + (double)Math.round((sellFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
}
}
}
Integer type = Integer.parseInt(entry.get("type"));
type = type <= 0 ? null : type;
int discount = disc.getDiscount(iH.getItemIDByName(iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type)), player);
if(discount > 0) {
double actualDiscount = (100 - discount) / 100D;
buyFor = Misc.Round(buyFor * actualDiscount, 2);
if(conf.getBoolean(GiantShop.getPlugin().getName() + ".discounts.affectsSales"))
sellFor = Misc.Round(sellFor * actualDiscount, 2);
}
String sf = String.valueOf(sellFor);
String bf = String.valueOf(buyFor);
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", entry.get("itemid"));
params.put("type", (!entry.get("type").equals("-1") ? entry.get("type") : "0"));
params.put("name", iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type));
params.put("perStack", entry.get("perstack"));
params.put("sellFor", (!sf.equals("-1.0") ? sf : "Not for sale!"));
params.put("buyFor", (!bf.equals("-1.0") ? bf : "No returns!"));
if(conf.getBoolean("GiantShop.stock.useStock") == true) {
params.put("stock", (!entry.get("stock").equals("-1") ? entry.get("stock") : "unlimited"));
params.put("maxStock", (!entry.get("maxstock").equals("-1") ? entry.get("maxstock") : "unlimited"));
}else{
params.put("stock", "unlimited");
params.put("maxStock", "unlimited");
}
// Future stuff
// Probably am going to want to do this VERY different though :D
/* if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(entry.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
* break;
* }
* }
* }else
*/
Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "list");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
| public static void list(Player player, String[] args) {
Messages msgs = GiantShop.getPlugin().getMsgHandler();
Items iH = GiantShop.getPlugin().getItemHandler();
Permission perms = GiantShop.getPlugin().getPermHandler().getEngine();
config conf = config.Obtain();
Discounter disc = GiantShop.getPlugin().getDiscounter();
if(perms.has(player, "giantshop.shop.list")) {
String name = GiantShop.getPlugin().getPubName();
int perPage = conf.getInt("GiantShop.global.perPage");
int curPag = 0;
if(args.length >= 2) {
try{
curPag = Integer.parseInt(args[1]);
}catch(NumberFormatException e) {
curPag = 1;
}
}else
curPag = 1;
curPag = (curPag > 0) ? curPag : 1;
iDriver DB = Database.Obtain().getEngine();
ArrayList<String> fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("perStack");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("maxStock");
fields.add("shops");
HashMap<String, HashMap<String, String>> where = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> t = new HashMap<String, String>();
if(conf.getBoolean("GiantShop.stock.hideEmptyStock")) {
t.put("kind", "NOT");
t.put("data", "0");
where.put("stock", t);
}
HashMap<String, String> order = new HashMap<String, String>();
order.put("itemID", "ASC");
order.put("type", "ASC");
ArrayList<HashMap<String, String>> data = DB.select(fields).from("#__items").where(where, true).orderBy(order).execQuery();
int pages = ((int)Math.ceil((double)data.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)data.size() / (double)perPage);
int start = (curPag * perPage) - perPage;
if(data.size() <= 0) {
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noItems"));
}else if(curPag > pages) {
Heraut.say(player, "&e[&3" + name + "&e]&c My Item list only has &e" + pages + " &cpages!!");
}else{
Heraut.say(player, "&e[&3" + name + "&e]&f Item list. Page: &e" + curPag + "&f/&e" + pages);
for(int i = start; i < (((start + perPage) > data.size()) ? data.size() : (start + perPage)); i++) {
HashMap<String, String> entry = data.get(i);
int stock = Integer.parseInt(entry.get("stock"));
int maxStock = Integer.parseInt(entry.get("maxstock"));
double sellFor = Double.parseDouble(entry.get("sellfor"));
double buyFor = Double.parseDouble(entry.get("buyfor"));
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) {
if(buyFor != -1)
buyFor = buyFor * (1.0 - maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 - maxDefl / 100.0);
}else if(stock <= atmi) {
if(buyFor != -1)
buyFor = buyFor * (1.0 + maxDefl / 100.0);
if(sellFor != -1)
sellFor = sellFor * (1.0 + maxDefl / 100.0);
}else{
if(stock < split) {
if(buyFor != -1)
buyFor = (double)Math.round((buyFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = (double)Math.round((sellFor * (1.0 + (maxInfl / stock) / 100)) * 100.0) / 100.0;
}else if(stock > split) {
if(buyFor != -1)
buyFor = 2.0 + (double)Math.round((buyFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
if(sellFor != -1)
sellFor = 2.0 + (double)Math.round((sellFor / (maxDefl * stock / 100)) * 100.0) / 100.0;
}
}
}
Integer type = Integer.parseInt(entry.get("type"));
type = type <= 0 ? null : type;
int discount = disc.getDiscount(iH.getItemIDByName(iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type)), player);
if(discount > 0) {
double actualDiscount = (100 - discount) / 100D;
buyFor = Misc.Round(buyFor * actualDiscount, 2);
if(conf.getBoolean(GiantShop.getPlugin().getName() + ".discounts.affectsSales"))
sellFor = Misc.Round(sellFor * actualDiscount, 2);
}
String sf = String.valueOf(sellFor);
String bf = String.valueOf(buyFor);
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", entry.get("itemid"));
params.put("type", (!entry.get("type").equals("-1") ? entry.get("type") : "0"));
params.put("name", iH.getItemNameByID(Integer.parseInt(entry.get("itemid")), type));
params.put("perStack", entry.get("perstack"));
params.put("sellFor", (!sf.equals("-1.0") && !sf.equals("-1") ? sf : "Not for sale!"));
params.put("buyFor", (!bf.equals("-1.0") && !sf.equals("-1") ? bf : "No returns!"));
if(conf.getBoolean("GiantShop.stock.useStock") == true) {
params.put("stock", (!entry.get("stock").equals("-1") ? entry.get("stock") : "unlimited"));
params.put("maxStock", (!entry.get("maxstock").equals("-1") ? entry.get("maxstock") : "unlimited"));
}else{
params.put("stock", "unlimited");
params.put("maxStock", "unlimited");
}
// Future stuff
// Probably am going to want to do this VERY different though :D
/* if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) {
* ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(entry.get("shops"));
* for(Indaface shop : shops) {
* if(shop.inShop(player.getLocation())) {
* Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
* break;
* }
* }
* }else
*/
Heraut.say(player, msgs.getMsg(Messages.msgType.MAIN, "itemListEntry", params));
}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "list");
Heraut.say(player, msgs.getMsg(Messages.msgType.ERROR, "noPermissions", data));
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityOilFabricator.java b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityOilFabricator.java
index deed6ec4..734f7aa5 100644
--- a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityOilFabricator.java
+++ b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityOilFabricator.java
@@ -1,45 +1,45 @@
package powercrystals.minefactoryreloaded.tile.machine;
import net.minecraft.block.Block;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraftforge.liquids.LiquidDictionary;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryInventory;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryPowered;
import powercrystals.minefactoryreloaded.gui.container.ContainerFactoryPowered;
import powercrystals.minefactoryreloaded.tile.base.TileEntityLiquidFabricator;
public class TileEntityOilFabricator extends TileEntityLiquidFabricator
{
public TileEntityOilFabricator()
{
- super((Integer)LiquidDictionary.getCanonicalLiquid("oil").itemID == null ? Block.waterStill.blockID : LiquidDictionary.getCanonicalLiquid("oil").itemID, 5880, 1);
+ super(LiquidDictionary.getCanonicalLiquid("oil") == null ? Block.waterStill.blockID : LiquidDictionary.getCanonicalLiquid("oil").itemID, 5880, 1);
}
@Override
public String getGuiBackground()
{
return "oilfab.png";
}
@Override
@SideOnly(Side.CLIENT)
public GuiFactoryInventory getGui(InventoryPlayer inventoryPlayer)
{
return new GuiFactoryPowered(getContainer(inventoryPlayer), this);
}
@Override
public ContainerFactoryPowered getContainer(InventoryPlayer inventoryPlayer)
{
return new ContainerFactoryPowered(this, inventoryPlayer);
}
@Override
public String getInvName()
{
return "Oil Fabricator";
}
}
| true | true | public TileEntityOilFabricator()
{
super((Integer)LiquidDictionary.getCanonicalLiquid("oil").itemID == null ? Block.waterStill.blockID : LiquidDictionary.getCanonicalLiquid("oil").itemID, 5880, 1);
}
| public TileEntityOilFabricator()
{
super(LiquidDictionary.getCanonicalLiquid("oil") == null ? Block.waterStill.blockID : LiquidDictionary.getCanonicalLiquid("oil").itemID, 5880, 1);
}
|
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
index 60f8e59d..8506f064 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/magetab/MageTabGenerator.java
@@ -1,778 +1,788 @@
/*
* Copyright 2009-2014 European Molecular Biology Laboratory
*
* 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 impl
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.fg.annotare2.web.server.magetab;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.IDF;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.SDRF;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.graph.Node;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.*;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.*;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.fg.annotare2.submission.model.*;
import uk.ac.ebi.fg.annotare2.web.server.ProtocolTypes;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Joiner.on;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Collections.emptyMap;
import static uk.ac.ebi.fg.annotare2.submission.model.ProtocolSubjectType.*;
import static uk.ac.ebi.fg.annotare2.submission.model.TermSource.EFO_TERM_SOURCE;
import static uk.ac.ebi.fg.annotare2.web.server.magetab.MageTabUtils.formatDate;
/**
* @author Olga Melnichuk
*/
public class MageTabGenerator {
private static class UnassignedValue {
private static final String TEMPLATE = "____UNASSIGNED____[SEQ]";
private static final String PATTERN = TEMPLATE.replace("[SEQ]", "\\d+");
private int seq = 1;
public String next() {
return TEMPLATE.replace("[SEQ]", Integer.toString(seq++));
}
public static String replaceAll(String string) {
return string.replaceAll(PATTERN, "");
}
}
public static String restoreAllUnassignedValues(String str) {
return UnassignedValue.replaceAll(str);
}
private static class UniqueNameValue {
private static final String TEMPLATE = "____[ORIGINAL_NAME]____[SEQ]____";
private static final Pattern PATTERN = Pattern.compile(
TEMPLATE.replace("____[ORIGINAL_NAME]____", "____(.*)____")
.replace("[SEQ]", "\\d+")
);
private int seq = 1;
public String next(String name) {
if (null == name) {
return null;
}
return TEMPLATE.replace("[SEQ]", Integer.toString(seq++))
.replace("[ORIGINAL_NAME]", name);
}
public static String replaceAll(String string) {
Matcher matcher = PATTERN.matcher(string);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).replaceAll("([\\\\$])", "\\\\$1"));
}
matcher.appendTail(sb);
return sb.toString();
}
}
public static String restoreOriginalNameValues(String str) {
return UniqueNameValue.replaceAll(str);
}
private final Map<String, SDRFNode> nodeCache = new HashMap<String, SDRFNode>();
private final Set<TermSource> usedTermSources = new HashSet<TermSource>();
private static ProtocolTypes protocolTypes = null;
private final UnassignedValue unassignedValue;
private final UniqueNameValue uniqueNameValue;
private final ExperimentProfile exp;
private final Set<GenerateOption> options;
private final String newLine;
public static enum GenerateOption {
REPLACE_NEWLINES_WITH_SPACES
}
public MageTabGenerator(ExperimentProfile exp, GenerateOption... options) {
if (null == protocolTypes) {
protocolTypes = ProtocolTypes.create();
}
this.options = new HashSet<GenerateOption>(Arrays.asList(options));
if (this.options.contains(GenerateOption.REPLACE_NEWLINES_WITH_SPACES)) {
newLine = " ";
} else {
newLine = System.getProperty("line.separator");
}
this.exp = exp;
this.unassignedValue = new UnassignedValue();
this.uniqueNameValue = new UniqueNameValue();
}
public MAGETABInvestigation generate() throws ParseException {
this.nodeCache.clear();
this.usedTermSources.clear();
MAGETABInvestigation inv = new MAGETABInvestigation();
generateIdf(inv.IDF);
generateSdrf(inv.SDRF);
addTermSources(inv.IDF);
return inv;
}
private void generateIdf(IDF idf) {
if (!isNullOrEmpty(exp.getAeExperimentType())) {
idf.addComment("AEExperimentType", exp.getAeExperimentType());
}
idf.investigationTitle = convertToIdfFriendly(exp.getTitle(), newLine);
idf.experimentDescription = convertToIdfFriendly(exp.getDescription(), newLine);
idf.publicReleaseDate = convertToIdfFriendly(formatDate(exp.getPublicReleaseDate()), newLine);
idf.dateOfExperiment = convertToIdfFriendly(formatDate(exp.getExperimentDate()), newLine);
idf.accession = convertToIdfFriendly(exp.getAccession(), newLine);
for (OntologyTerm term : exp.getExperimentalDesigns()) {
idf.experimentalDesign.add(convertToIdfFriendly(term.getLabel(), newLine));
idf.experimentalDesignTermAccession.add(convertToIdfFriendly(term.getAccession(), newLine));
idf.experimentalDesignTermSourceREF.add(ensureTermSource(EFO_TERM_SOURCE).getName());
}
for (Contact contact : exp.getContacts()) {
idf.personFirstName.add(convertToIdfFriendly(contact.getFirstName(), newLine));
idf.personLastName.add(convertToIdfFriendly(contact.getLastName(), newLine));
idf.personMidInitials.add(convertToIdfFriendly(contact.getMidInitials(), newLine));
idf.personEmail.add(convertToIdfFriendly(contact.getEmail(), newLine));
idf.personPhone.add(convertToIdfFriendly(contact.getPhone(), newLine));
idf.personFax.add(convertToIdfFriendly(contact.getFax(), newLine));
idf.personAddress.add(convertToIdfFriendly(contact.getAddress(), newLine));
idf.personAffiliation.add(convertToIdfFriendly(contact.getAffiliation(), newLine));
idf.personRoles.add(joinCollection(contact.getRoles(), ";"));
}
for (Publication publication : exp.getPublications()) {
idf.publicationTitle.add(convertToIdfFriendly(publication.getTitle(), newLine));
idf.publicationAuthorList.add(convertToIdfFriendly(publication.getAuthors(), newLine));
idf.pubMedId.add(convertToIdfFriendly(publication.getPubMedId(), newLine));
idf.publicationDOI.add(convertToIdfFriendly(publication.getDoi(), newLine));
OntologyTerm status = publication.getStatus();
idf.publicationStatus.add(convertToIdfFriendly(status == null ? null : status.getLabel(), newLine));
idf.publicationStatusTermAccession.add(convertToIdfFriendly(status == null ? null : status.getAccession(), newLine));
idf.publicationStatusTermSourceREF.add(convertToIdfFriendly(status == null ? null : ensureTermSource(EFO_TERM_SOURCE).getName(), newLine));
}
for (Protocol protocol : exp.getProtocols()) {
if (protocol.isAssigned()) {
idf.protocolName.add(convertToIdfFriendly(protocol.getName(), newLine));
idf.protocolDescription.add(convertToIdfFriendly(protocol.getDescription(), newLine));
idf.protocolType.add(convertToIdfFriendly(protocol.getType().getLabel(), newLine));
idf.protocolTermAccession.add(convertToIdfFriendly(protocol.getType().getAccession(), newLine));
idf.protocolTermSourceREF.add(ensureTermSource(EFO_TERM_SOURCE).getName());
idf.protocolHardware.add(convertToIdfFriendly(protocol.getHardware(), newLine));
idf.protocolSoftware.add(convertToIdfFriendly(protocol.getSoftware(), newLine));
}
}
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (!attribute.getType().isFactorValue()) {
continue;
}
idf.experimentalFactorName.add(convertToIdfFriendly(getName(attribute), newLine));
OntologyTerm term = attribute.getTerm();
if (term != null) {
idf.experimentalFactorType.add(convertToIdfFriendly(term.getLabel(), newLine));
idf.experimentalFactorTermAccession.add(convertToIdfFriendly(term.getAccession(), newLine));
idf.experimentalFactorTermSourceREF.add(convertToIdfFriendly(ensureTermSource(EFO_TERM_SOURCE).getName(), newLine));
} else {
idf.experimentalFactorType.add(convertToIdfFriendly(getName(attribute), newLine));
idf.experimentalFactorTermAccession.add("");
idf.experimentalFactorTermSourceREF.add("");
}
}
}
private void addTermSources(IDF idf) {
for (TermSource termSource : usedTermSources) {
idf.termSourceName.add(convertToIdfFriendly(termSource.getName(), newLine));
idf.termSourceVersion.add(convertToIdfFriendly(termSource.getVersion(), newLine));
idf.termSourceFile.add(convertToIdfFriendly(termSource.getUrl(), newLine));
}
}
private String nodeId(Class<?> clazz, String name) {
return clazz + "@" + name;
}
private <T extends SDRFNode> T createFakeNode(Class<T> clazz) {
return createNode(clazz, unassignedValue.next());
}
private <T extends SDRFNode> T createNode(Class<T> clazz, String name) {
try {
T t = clazz.newInstance();
t.setNodeName(name);
nodeCache.put(nodeId(clazz, name), t);
return t;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private <T extends SDRFNode> T getNode(Class<T> clazz, String name) {
return (T) nodeCache.get(nodeId(clazz, name));
}
private <T extends SDRFNode> T getOrCreateNode(Class<T> clazz, String nodeName) {
if (isNullOrEmpty(nodeName)) {
return createFakeNode(clazz);
}
T node = getNode(clazz, nodeName);
if (null == node) {
node = createNode(clazz, nodeName);
}
return node;
}
private void generateSdrf(SDRF sdrf) throws ParseException {
Map<Integer, SDRFNode> sourceLayer = generateSourceNodes();
for (SDRFNode node : sourceLayer.values()) {
sdrf.addNode(node);
}
Map<Integer, SDRFNode> extractLayer = generateExtractNodes(sourceLayer);
if (exp.getType().isMicroarray()) {
Map<String, SDRFNode> labeledExtractLayer = generateLabeledExtractNodes(extractLayer);
generateMicroarrayAssayScanAndDataFileNodes(sdrf, labeledExtractLayer);
} else {
generateSeqAssayNodesAndDataFileNodes(extractLayer);
}
}
private Map<Integer, SDRFNode> generateSourceNodes() {
Map<Integer, SDRFNode> layer = new LinkedHashMap<Integer, SDRFNode>();
for (Sample sample : exp.getSamples()) {
layer.put(sample.getId(), createSourceNode(sample));
}
return layer;
}
private Map<Integer, SDRFNode> generateExtractNodes(Map<Integer, SDRFNode> sampleLayer) {
if (sampleLayer.isEmpty() || exp.getExtracts().isEmpty()) {
return emptyMap();
}
Map<Integer, SDRFNode> layer = new LinkedHashMap<Integer, SDRFNode>();
int fakeId = -1;
for (Integer sampleId : sampleLayer.keySet()) {
Sample sample = exp.getSample(sampleId);
SDRFNode sampleNode = sampleLayer.get(sampleId);
Collection<Extract> extracts = exp.getExtracts(sample);
Collection<Protocol> protocols = exp.getProtocols(sample);
if (extracts.isEmpty()) {
layer.put(fakeId--, createExtractNode(null, sampleNode, protocols));
}
for (Extract extract : extracts) {
layer.put(extract.getId(), createExtractNode(extract, sampleNode, protocols));
}
}
return layer;
}
private Map<String, SDRFNode> generateLabeledExtractNodes(Map<Integer, SDRFNode> extractLayer) {
if (extractLayer.isEmpty() || exp.getLabeledExtracts().isEmpty()) {
return emptyMap();
}
Map<String, SDRFNode> layer = new LinkedHashMap<String, SDRFNode>();
int fakeId = -1;
for (Integer extractId : extractLayer.keySet()) {
Extract extract = exp.getExtract(extractId);
SDRFNode extractNode = extractLayer.get(extractId);
Collection<LabeledExtract> labeledExtracts = extract == null ?
Collections.<LabeledExtract>emptyList() : exp.getLabeledExtracts(extract);
Collection<Protocol> protocols = exp.getProtocols(extract);
if (labeledExtracts.isEmpty()) {
layer.put("" + (fakeId--), createLabeledExtractNode(null, extractNode, protocols));
}
for (LabeledExtract labeledExtract : labeledExtracts) {
layer.put(labeledExtract.getId(), createLabeledExtractNode(labeledExtract, extractNode, protocols));
}
}
return layer;
}
private void generateMicroarrayAssayScanAndDataFileNodes(SDRF sdrf, Map<String, SDRFNode> labeledExtractLayer) {
// no labeled extracts supplied? no assays can be generated
if (labeledExtractLayer.isEmpty()) {
return;
}
// no files uploaded? no assays can be generated
Collection<FileColumn> fileColumns = exp.getFileColumns();
if (fileColumns.isEmpty()) {
return;
}
// create assay name per labeledExtractId map
Map<String, String> leIds2assayName = new HashMap<String, String>();
for (FileColumn fileColumn : fileColumns) {
if (!fileColumn.getType().isFGEM()) {
for (String leId : labeledExtractLayer.keySet()) {
FileRef fileRef = fileColumn.getFileRef(leId);
leIds2assayName.put(leId, null != fileRef ? removeExtension(fileRef.getName()) : null);
}
break;
}
}
Map<String, SDRFNode> nextLayer = new LinkedHashMap<String, SDRFNode>();
for (String leId : labeledExtractLayer.keySet()) {
LabeledExtract labeledExtract = exp.getLabeledExtract(leId);
SDRFNode leNode = labeledExtractLayer.get(leId);
Collection<Protocol> leProtocols = exp.getProtocols(labeledExtract);
String assayName = leNode.getNodeName();
if (!leIds2assayName.isEmpty()) {
assayName = leIds2assayName.containsKey(leId) ? leIds2assayName.get(leId) : null;
}
SDRFNode assayNode = createAssayNode(assayName, leNode, leProtocols, sdrf);
nextLayer.put(leId, assayNode);
+ boolean isRawDataPresent = false;
for (FileColumn fileColumn : fileColumns) {
FileRef fileRef = fileColumn.getFileRef(leId);
+ FileType colType = fileColumn.getType();
+ if (!isRawDataPresent && colType.isRaw()) {
+ isRawDataPresent = true;
+ }
//boolean isFirstColumn = fileColumn.equals(fileColumns.iterator().next());
//List<ProtocolSubjectType> protocolSubjectTypes = new ArrayList<ProtocolSubjectType>();
//if (isFirstColumn) {
// protocolSubjectTypes.add(FILE);
//}
//protocolSubjectTypes.add(fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE);
- Collection<Protocol> protocols = null != fileRef ?
- exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE, FILE) :
- Collections.<Protocol>emptyList();
+ Collection<Protocol> protocols = Collections.<Protocol>emptyList();
+ if (null != fileRef) {
+ if ((isRawDataPresent && colType.isRaw()) || (!isRawDataPresent && colType.isProcessed())) {
+ protocols = exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE, FILE);
+ } else {
+ protocols = exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE);
+ }
+ }
// for the first column check if there are array scanning protocol(s) defined
// add scan object if necessary
//if (isFirstColumn) {
// boolean isScanProtocolDefined = Iterables.any(protocols, new Predicate<Protocol>() {
// @Override
// public boolean apply(@Nullable Protocol protocol) {
// return null != protocol && "EFO_0003814".equals(protocol.getType().getAccession());
// }
// });
//
// if (isScanProtocolDefined) {
// nextLayer.put(leId, createScanNode(nextLayer.get(leId), Collections.<Protocol>emptyList()));
// }
//}
SDRFNode fileNode = createFileNode(nextLayer.get(leId), fileColumn.getType(), fileRef, protocols);
nextLayer.put(leId, fileNode);
}
}
}
private String removeExtension(String fileName) {
return (null != fileName ? fileName.replaceAll("^(.+)[.][^.]*$", "$1") : null);
}
private void generateSeqAssayNodesAndDataFileNodes(Map<Integer, SDRFNode> extractLayer) {
// no extracts supplied? no assays can be generated
if (extractLayer.isEmpty()) {
return;
}
FileType[] fileTypesInOrder = new FileType[] {FileType.RAW_FILE, FileType.PROCESSED_FILE, FileType.PROCESSED_MATRIX_FILE};
MultiSets<Integer, SDRFNode> nextLayer = new MultiSets<Integer, SDRFNode>();
for (Integer extractId : extractLayer.keySet()) {
Extract extract = exp.getExtract(extractId);
SDRFNode extractNode = extractLayer.get(extractId);
Collection<Protocol> eProtocols = exp.getProtocols(extract);
String assayName = extractNode.getNodeName();
SDRFNode assayNode = createAssayNode(assayName, extractNode, eProtocols, null);
nextLayer.put(extractId, assayNode);
for (FileType fileType : fileTypesInOrder) {
Set<SDRFNode> sourceNodes = nextLayer.get(extractId);
nextLayer.remove(extractId);
for (FileColumn fileColumn : exp.getFileColumns(fileType)) {
FileRef fileRef = fileColumn.getFileRef(String.valueOf(extractId));
Collection<Protocol> protocols = null != fileRef ?
exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE) :
Collections.<Protocol>emptyList();
SDRFNode fileNode = createFileNode(sourceNodes, fileColumn.getType(), fileRef, protocols);
nextLayer.put(extractId, fileNode);
if (!fileType.isRaw()) {
sourceNodes = nextLayer.get(extractId);
nextLayer.remove(extractId);
}
}
}
}
}
private void connect(SDRFNode source, SDRFNode destination, Collection<Protocol> protocols) {
SDRFNode prev = source;
Collection<Protocol> orderedProtocols =
Ordering.natural().onResultOf(new Function<Protocol, Integer>() {
@Override
public Integer apply(Protocol protocol) {
return protocolTypes.getPrecedence(protocol.getType().getAccession());
}
}).sortedCopy(protocols);
for (Protocol protocol : orderedProtocols) {
// protocol node name must be unique
String nodeName = prev.getClass().getSimpleName() + ":" + prev.getNodeName() + ":" + protocol.getId() + (protocol.isAssigned() ? "" : "F");
ProtocolApplicationNode protocolNode = getNode(ProtocolApplicationNode.class, nodeName);
if (null == protocolNode) {
if (protocol.isAssigned()) {
protocolNode = createNode(ProtocolApplicationNode.class, nodeName);
protocolNode.protocol = protocol.getName();
if (protocol.hasPerformer()) {
PerformerAttribute attr = new PerformerAttribute();
attr.setAttributeValue(protocol.getPerformer());
protocolNode.performer = attr;
}
}
}
if (null != protocolNode) {
connect(prev, protocolNode);
prev = protocolNode;
}
}
connect(prev, destination);
}
private void connect(SDRFNode source, SDRFNode destination) {
source.addChildNode(destination);
destination.addParentNode(source);
}
private SourceNode createSourceNode(Sample sample) {
SourceNode sourceNode = getNode(SourceNode.class, sample.getName());
if (sourceNode != null) {
return sourceNode;
}
sourceNode = createNode(SourceNode.class, sample.getName());
sourceNode.characteristics.addAll(extractCharacteristicsAttributes(sample));
sourceNode.materialType = extractMaterialTypeAttribute(sample);
sourceNode.provider = extractProviderAttribute(sample);
sourceNode.description = extractDescriptionAttribute(sample);
return sourceNode;
}
private ExtractNode createExtractNode(Extract extract, SDRFNode sampleNode, Collection<Protocol> protocols) {
ExtractNode extractNode;
if (extract == null) {
extractNode = createFakeNode(ExtractNode.class);
} else {
extractNode = getNode(ExtractNode.class, extract.getName());
if (extractNode != null) {
return extractNode;
}
extractNode = createNode(ExtractNode.class, extract.getName());
for (ExtractAttribute attr : ExtractAttribute.values()) {
String value = extract.getAttributeValue(attr);
if (!isNullOrEmpty(value)) {
extractNode.comments.put(getSdrfFriendlyName(attr), Arrays.asList(value));
}
}
}
connect(sampleNode, extractNode, protocols);
return extractNode;
}
private static String getSdrfFriendlyName(ExtractAttribute attr) {
switch (attr) {
case LIBRARY_LAYOUT:
return "LIBRARY_LAYOUT";
case LIBRARY_SELECTION:
return "LIBRARY_SELECTION";
case LIBRARY_SOURCE:
return "LIBRARY_SOURCE";
case LIBRARY_STRATEGY:
return "LIBRARY_STRATEGY";
default:
return attr.getTitle();
}
}
private LabeledExtractNode createLabeledExtractNode(LabeledExtract labeledExtract, SDRFNode extractNode, Collection<Protocol> protocols) {
LabeledExtractNode labeledExtractNode;
String label;
if (labeledExtract == null) {
labeledExtractNode = createFakeNode(LabeledExtractNode.class);
label = labeledExtractNode.getNodeName();
} else {
labeledExtractNode = getNode(LabeledExtractNode.class, labeledExtract.getName());
if (labeledExtractNode != null) {
return labeledExtractNode;
}
labeledExtractNode = createNode(LabeledExtractNode.class, labeledExtract.getName());
label = labeledExtract.getLabel().getName();
}
LabelAttribute labelAttribute = new LabelAttribute();
labelAttribute.setAttributeValue(label);
labeledExtractNode.label = labelAttribute;
connect(extractNode, labeledExtractNode, protocols);
return labeledExtractNode;
}
private AssayNode createAssayNode(String assayName, SDRFNode prevNode, Collection<Protocol> protocols, SDRF sdrf) {
AssayNode assayNode;
if (!isNullOrEmpty(assayName)) {
assayNode = getNode(AssayNode.class, assayName);
if (assayNode != null) {
addFactorValues(assayNode, prevNode, sdrf);
connect(prevNode, assayNode, protocols);
return assayNode;
}
assayNode = createNode(AssayNode.class, assayName);
} else {
assayNode = createFakeNode(AssayNode.class);
}
assayNode.technologyType = createTechnologyTypeAttribute();
ArrayDesignAttribute arrayDesignAttribute = createArrayDesignAttribute();
if (arrayDesignAttribute != null) {
assayNode.arrayDesigns.add(arrayDesignAttribute);
}
addFactorValues(assayNode, prevNode, sdrf);
connect(prevNode, assayNode, protocols);
return assayNode;
}
private void addFactorValues(AssayNode assayNode, SDRFNode prevNode, SDRF sdrf) {
Collection<Sample> samples = findSamples(prevNode);
if (samples.size() > 1) {
throw new IllegalStateException("Too many samples");
}
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (!attribute.getType().isFactorValue()) {
continue;
}
for (Sample sample : samples) {
FactorValueAttribute attr = new FactorValueAttribute();
attr.type = getName(attribute);
attr.unit = createUnitAttribute(attribute.getUnits());
attr.setAttributeValue(sample.getValue(attribute));
//TODO if attr value is an EFO Term then fill in accession and source REF
//attr.termAccessionNumber = term.getAccession();
//attr.termSourceREF = ensureTermSource(TermSource.EFO_TERM_SOURCE).getName();
if (prevNode instanceof LabeledExtractNode && null != sdrf) {
String label = ((LabeledExtractNode)prevNode).label.getAttributeValue();
attr.scannerChannel = sdrf.getChannelNumber(label);
}
assayNode.factorValues.add(attr);
}
}
}
private TechnologyTypeAttribute createTechnologyTypeAttribute() {
TechnologyTypeAttribute technologyType = new TechnologyTypeAttribute();
technologyType.setAttributeValue(
exp.getType().isMicroarray() ? "array assay" : "sequencing assay");
return technologyType;
}
private ArrayDesignAttribute createArrayDesignAttribute() {
String arrayDesign = exp.getArrayDesign();
if (isNullOrEmpty(arrayDesign)) {
return null;
}
ArrayDesignAttribute arrayDesignAttribute = new ArrayDesignAttribute();
arrayDesignAttribute.setAttributeValue(arrayDesign);
arrayDesignAttribute.termSourceREF = ensureTermSource(TermSource.ARRAY_EXPRESS_TERM_SOURCE).getName();
return arrayDesignAttribute;
}
private Collection<Sample> findSamples(SDRFNode node) {
List<SourceNode> sourceNodes = new ArrayList<SourceNode>();
Queue<Node> nodes = new ArrayDeque<Node>();
nodes.add(node);
while (!nodes.isEmpty()) {
Node next = nodes.poll();
for (Node parent : next.getParentNodes()) {
if (parent instanceof SourceNode) {
sourceNodes.add((SourceNode) parent);
} else {
nodes.addAll(next.getParentNodes());
}
}
}
List<Sample> samples = new ArrayList<Sample>();
for (SourceNode sourceNode : sourceNodes) {
Sample sample = exp.getSampleByName(sourceNode.getNodeName());
if (sample != null) {
samples.add(sample);
}
}
return samples;
}
private ScanNode createScanNode(SDRFNode assayNode, Collection<Protocol> protocols) {
ScanNode scanNode = getOrCreateNode(ScanNode.class, assayNode.getNodeName());
if (null == scanNode) {
scanNode = createNode(ScanNode.class, assayNode.getNodeName());
}
connect(assayNode, scanNode, protocols);
return scanNode;
}
private SDRFNode createFileNode(SDRFNode prevNode, FileType fileType, FileRef fileRef, Collection<Protocol> protocols) {
Set<SDRFNode> prevNodes = new HashSet<SDRFNode>();
prevNodes.add(prevNode);
return createFileNode(prevNodes, fileType, fileRef, protocols);
}
private SDRFNode createFileNode(Set<SDRFNode> prevNodes, FileType fileType, FileRef fileRef, Collection<Protocol> protocols) {
SDRFNode fileNode;
String fileName = null != fileRef ? fileRef.getName() : null;
switch (fileType) {
case RAW_FILE:
ArrayDataNode rawFileNode = getOrCreateNode(ArrayDataNode.class, fileName);
if (exp.getType().isSequencing() && rawFileNode.comments.isEmpty()) {
rawFileNode.comments.put("MD5", Arrays.asList(null != fileRef ? fileRef.getHash() : null));
}
fileNode = rawFileNode;
break;
case RAW_MATRIX_FILE:
fileNode = getOrCreateNode(ArrayDataMatrixNode.class, uniqueNameValue.next(fileName));
break;
case PROCESSED_FILE:
fileNode = getOrCreateNode(DerivedArrayDataNode.class, fileName);
break;
case PROCESSED_MATRIX_FILE:
fileNode = getOrCreateNode(DerivedArrayDataMatrixNode.class, fileName);
break;
default:
throw new IllegalStateException("Unsupported file type: " + fileType);
}
for (SDRFNode prevNode : prevNodes) {
connect(prevNode, fileNode, protocols);
}
return fileNode;
}
private TermSource ensureTermSource(TermSource termSource) {
usedTermSources.add(termSource);
return termSource;
}
private MaterialTypeAttribute extractMaterialTypeAttribute(Sample sample) {
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (attribute.getType().isMaterialType()) {
MaterialTypeAttribute attr = new MaterialTypeAttribute();
attr.setAttributeValue(sample.getValue(attribute));
return attr;
}
}
return null;
}
private ProviderAttribute extractProviderAttribute(Sample sample) {
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (attribute.getType().isProvider()) {
ProviderAttribute attr = new ProviderAttribute();
attr.setAttributeValue(sample.getValue(attribute));
return attr;
}
}
return null;
}
private String extractDescriptionAttribute(Sample sample) {
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (attribute.getType().isDescription()) {
return sample.getValue(attribute);
}
}
return null;
}
private List<CharacteristicsAttribute> extractCharacteristicsAttributes(Sample sample) {
List<CharacteristicsAttribute> attributes = new ArrayList<CharacteristicsAttribute>();
for (SampleAttribute attribute : exp.getSampleAttributes()) {
if (attribute.getType().isCharacteristic()) {
CharacteristicsAttribute attr = new CharacteristicsAttribute();
attr.type = getName(attribute);
attr.unit = createUnitAttribute(attribute.getUnits());
attr.setAttributeValue(sample.getValue(attribute));
//TODO if value is an EFO term fill in accession and term source
//attr.termAccessionNumber = term.getAccession();
//attr.termSourceREF = ensureTermSource(TermSource.EFO_TERM_SOURCE).getName();
attributes.add(attr);
}
}
return attributes;
}
private UnitAttribute createUnitAttribute(OntologyTerm units) {
if (units == null) {
return null;
}
UnitAttribute attr = new UnitAttribute();
attr.type = units.getLabel();
attr.setAttributeValue(units.getLabel());
attr.termSourceREF = ensureTermSource(TermSource.EFO_TERM_SOURCE).getName();
attr.termAccessionNumber = units.getAccession();
return attr;
}
private String getName(SampleAttribute attr) {
OntologyTerm term = attr.getTerm();
return term != null ? term.getLabel() :
attr.getName() != null ? attr.getName().toLowerCase() :
null;
}
private static String convertToIdfFriendly(String str, String newLine) {
return str == null || str.trim().isEmpty() ? "" : str.replaceAll("(\\r\\n|[\\r\\n])", newLine);
}
private static String joinCollection(Collection<String> collection, String separator) {
return on(separator).join(collection);
}
}
| false | true | private void generateMicroarrayAssayScanAndDataFileNodes(SDRF sdrf, Map<String, SDRFNode> labeledExtractLayer) {
// no labeled extracts supplied? no assays can be generated
if (labeledExtractLayer.isEmpty()) {
return;
}
// no files uploaded? no assays can be generated
Collection<FileColumn> fileColumns = exp.getFileColumns();
if (fileColumns.isEmpty()) {
return;
}
// create assay name per labeledExtractId map
Map<String, String> leIds2assayName = new HashMap<String, String>();
for (FileColumn fileColumn : fileColumns) {
if (!fileColumn.getType().isFGEM()) {
for (String leId : labeledExtractLayer.keySet()) {
FileRef fileRef = fileColumn.getFileRef(leId);
leIds2assayName.put(leId, null != fileRef ? removeExtension(fileRef.getName()) : null);
}
break;
}
}
Map<String, SDRFNode> nextLayer = new LinkedHashMap<String, SDRFNode>();
for (String leId : labeledExtractLayer.keySet()) {
LabeledExtract labeledExtract = exp.getLabeledExtract(leId);
SDRFNode leNode = labeledExtractLayer.get(leId);
Collection<Protocol> leProtocols = exp.getProtocols(labeledExtract);
String assayName = leNode.getNodeName();
if (!leIds2assayName.isEmpty()) {
assayName = leIds2assayName.containsKey(leId) ? leIds2assayName.get(leId) : null;
}
SDRFNode assayNode = createAssayNode(assayName, leNode, leProtocols, sdrf);
nextLayer.put(leId, assayNode);
for (FileColumn fileColumn : fileColumns) {
FileRef fileRef = fileColumn.getFileRef(leId);
//boolean isFirstColumn = fileColumn.equals(fileColumns.iterator().next());
//List<ProtocolSubjectType> protocolSubjectTypes = new ArrayList<ProtocolSubjectType>();
//if (isFirstColumn) {
// protocolSubjectTypes.add(FILE);
//}
//protocolSubjectTypes.add(fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE);
Collection<Protocol> protocols = null != fileRef ?
exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE, FILE) :
Collections.<Protocol>emptyList();
// for the first column check if there are array scanning protocol(s) defined
// add scan object if necessary
//if (isFirstColumn) {
// boolean isScanProtocolDefined = Iterables.any(protocols, new Predicate<Protocol>() {
// @Override
// public boolean apply(@Nullable Protocol protocol) {
// return null != protocol && "EFO_0003814".equals(protocol.getType().getAccession());
// }
// });
//
// if (isScanProtocolDefined) {
// nextLayer.put(leId, createScanNode(nextLayer.get(leId), Collections.<Protocol>emptyList()));
// }
//}
SDRFNode fileNode = createFileNode(nextLayer.get(leId), fileColumn.getType(), fileRef, protocols);
nextLayer.put(leId, fileNode);
}
}
}
| private void generateMicroarrayAssayScanAndDataFileNodes(SDRF sdrf, Map<String, SDRFNode> labeledExtractLayer) {
// no labeled extracts supplied? no assays can be generated
if (labeledExtractLayer.isEmpty()) {
return;
}
// no files uploaded? no assays can be generated
Collection<FileColumn> fileColumns = exp.getFileColumns();
if (fileColumns.isEmpty()) {
return;
}
// create assay name per labeledExtractId map
Map<String, String> leIds2assayName = new HashMap<String, String>();
for (FileColumn fileColumn : fileColumns) {
if (!fileColumn.getType().isFGEM()) {
for (String leId : labeledExtractLayer.keySet()) {
FileRef fileRef = fileColumn.getFileRef(leId);
leIds2assayName.put(leId, null != fileRef ? removeExtension(fileRef.getName()) : null);
}
break;
}
}
Map<String, SDRFNode> nextLayer = new LinkedHashMap<String, SDRFNode>();
for (String leId : labeledExtractLayer.keySet()) {
LabeledExtract labeledExtract = exp.getLabeledExtract(leId);
SDRFNode leNode = labeledExtractLayer.get(leId);
Collection<Protocol> leProtocols = exp.getProtocols(labeledExtract);
String assayName = leNode.getNodeName();
if (!leIds2assayName.isEmpty()) {
assayName = leIds2assayName.containsKey(leId) ? leIds2assayName.get(leId) : null;
}
SDRFNode assayNode = createAssayNode(assayName, leNode, leProtocols, sdrf);
nextLayer.put(leId, assayNode);
boolean isRawDataPresent = false;
for (FileColumn fileColumn : fileColumns) {
FileRef fileRef = fileColumn.getFileRef(leId);
FileType colType = fileColumn.getType();
if (!isRawDataPresent && colType.isRaw()) {
isRawDataPresent = true;
}
//boolean isFirstColumn = fileColumn.equals(fileColumns.iterator().next());
//List<ProtocolSubjectType> protocolSubjectTypes = new ArrayList<ProtocolSubjectType>();
//if (isFirstColumn) {
// protocolSubjectTypes.add(FILE);
//}
//protocolSubjectTypes.add(fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE);
Collection<Protocol> protocols = Collections.<Protocol>emptyList();
if (null != fileRef) {
if ((isRawDataPresent && colType.isRaw()) || (!isRawDataPresent && colType.isProcessed())) {
protocols = exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE, FILE);
} else {
protocols = exp.getProtocols(fileRef, fileColumn.getType().isRaw() ? RAW_FILE : PROCESSED_FILE);
}
}
// for the first column check if there are array scanning protocol(s) defined
// add scan object if necessary
//if (isFirstColumn) {
// boolean isScanProtocolDefined = Iterables.any(protocols, new Predicate<Protocol>() {
// @Override
// public boolean apply(@Nullable Protocol protocol) {
// return null != protocol && "EFO_0003814".equals(protocol.getType().getAccession());
// }
// });
//
// if (isScanProtocolDefined) {
// nextLayer.put(leId, createScanNode(nextLayer.get(leId), Collections.<Protocol>emptyList()));
// }
//}
SDRFNode fileNode = createFileNode(nextLayer.get(leId), fileColumn.getType(), fileRef, protocols);
nextLayer.put(leId, fileNode);
}
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java
index 9729a5253..e9c1e28d3 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java
@@ -1,377 +1,377 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// 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 com.puppycrawl.tools.checkstyle;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashSet;
import org.apache.regexp.RESyntaxException;
/**
* This class provides the functionality to check a set of files.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
* @author <a href="mailto:[email protected]">Stephane Bailliez</a>
*/
public class Checker
implements Defn
{
/**
* Overrides ANTLR error reporting so we completely control
* checkstyle's output during parsing. This is important because
* we try parsing with several grammers (with/without support for
* <code>assert</code>). We must not write any error messages when
* parsing fails because with the next grammar it might succeed
* and the user will be confused.
*/
private class SilentJava14Recognizer extends GeneratedJava14Recognizer
{
/**
* Creates a new <code>SilentJava14Recognizer</code> instance.
*
* @param aLexer the tokenstream the recognizer operates on.
*/
private SilentJava14Recognizer(GeneratedJava14Lexer aLexer)
{
super(aLexer);
}
/**
* Parser error-reporting function, does nothing.
* @param aRex the exception to be reported
*/
public void reportError(RecognitionException aRex)
{
}
/**
* Parser error-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportError(String aMsg)
{
}
/**
* Parser warning-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportWarning(String aMsg)
{
}
}
/** configuration */
private final Configuration mConfig;
/** cache file **/
private final PropertyCacheFile mCache;
/** vector of listeners */
private final ArrayList mListeners = new ArrayList();
/**
* Constructs the object.
* @param aConfig contains the configuration to check with
* @throws RESyntaxException unable to create a regexp object
**/
public Checker(Configuration aConfig)
throws RESyntaxException
{
mConfig = aConfig;
mCache = new PropertyCacheFile(aConfig);
final Verifier v = new Verifier(aConfig);
VerifierSingleton.setInstance(v);
}
/** Cleans up the object **/
public void destroy()
{
mCache.destroy();
mListeners.clear();
}
/**
* Add the listener that will be used to receive events from the audit
* @param aListener the nosy thing
*/
public void addListener(AuditListener aListener)
{
mListeners.add(aListener);
}
/**
* Processes a set of files.
* Once this is done, it is highly recommended to call for
* the destroy method to close and remove the listeners.
* @param aFiles the list of files to be audited.
* @return the total number of errors found
* @see #destroy()
*/
public int process(String[] aFiles)
{
int total = 0;
fireAuditStarted();
// If you move checkPackageHtml() around beware of the caching
// functionality of checkstyle. Make sure that package.html
// checks are not skipped because of caching. Otherwise you
// might e.g. have a package.html file, check all java files
// without errors, delete package.html and then recheck without
// errors because the html file is not covered by the cache.
total += checkPackageHtml(aFiles);
for (int i = 0; i < aFiles.length; i++) {
total += process(aFiles[i]);
}
fireAuditFinished();
return total;
}
/**
* Processes a specified file and prints out all errors found.
* @return the number of errors found
* @param aFileName the name of the file to process
**/
private int process(String aFileName)
{
// check if already checked and passed the file
final File f = new File(aFileName);
final long timestamp = f.lastModified();
if (mCache.alreadyChecked(aFileName, timestamp)) {
return 0;
}
// Create a stripped down version
final String stripped;
- if ((mConfig.getBasedir() == null)
- || !aFileName.startsWith(mConfig.getBasedir()))
- {
+ final String basedir = mConfig.getBasedir();
+ if ((basedir == null) || !aFileName.startsWith(basedir)) {
stripped = aFileName;
}
else {
// making the assumption that there is text after basedir
- stripped = aFileName.substring(mConfig.getBasedir().length() + 1);
+ final int skipSep = basedir.endsWith(File.separator) ? 0 : 1;
+ stripped = aFileName.substring(basedir.length() + skipSep);
}
LineText[] errors;
try {
fireFileStarted(stripped);
final String[] lines = getLines(aFileName);
try {
// try the 1.4 grammar first, this will succeed for
// all code that compiles without any warnings in JDK 1.4,
// that should cover most cases
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJava14Lexer jl = new GeneratedJava14Lexer(sar);
jl.setFilename(aFileName);
final GeneratedJava14Recognizer jr =
new SilentJava14Recognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
catch (RecognitionException re) {
// Parsing might have failed because the checked
// file contains "assert" as an identifier. Retry with a
// grammar that treats "assert" as an identifier
// and not as a keyword
// Arghh - the pain - duplicate code!
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJavaLexer jl = new GeneratedJavaLexer(sar);
jl.setFilename(aFileName);
final GeneratedJavaRecognizer jr =
new GeneratedJavaRecognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
errors = VerifierSingleton.getInstance().getMessages();
}
catch (FileNotFoundException fnfe) {
errors = new LineText[] {new LineText(0, "File not found!")};
}
catch (IOException ioe) {
errors = new LineText[] {
new LineText(0, "Got an IOException -" + ioe.getMessage())};
}
catch (RecognitionException re) {
errors = new LineText[] {
new LineText(0,
"Got a RecognitionException -" + re.getMessage())};
}
catch (TokenStreamException te) {
errors = new LineText[] {
new LineText(0,
"Got a TokenStreamException -" + te.getMessage())};
}
if (errors.length == 0) {
mCache.checkedOk(aFileName, timestamp);
}
else {
fireErrors(stripped, errors);
}
fireFileFinished(stripped);
return errors.length;
}
/**
* Checks for a package.html file for all java files in parameter list.
* @param aFiles the filenames of the java files to check
* @return the number of errors found
*/
private int checkPackageHtml(String[] aFiles)
{
if (!mConfig.isRequirePackageHtml()) {
return 0;
}
int packageHtmlErrors = 0;
final HashSet checkedPackages = new HashSet();
for (int i = 0; i < aFiles.length; i++) {
final File file = new File(aFiles[i]);
final File packageDir = file.getParentFile();
if (!checkedPackages.contains(packageDir)) {
final File packageDoc =
new File(packageDir, "package.html");
final String docFile = packageDoc.toString();
fireFileStarted(docFile);
if (!packageDoc.exists()) {
final LineText error =
new LineText(0, "missing package documentation file.");
fireErrors(docFile, new LineText[]{error});
packageHtmlErrors++;
}
fireFileFinished(docFile);
checkedPackages.add(packageDir);
}
}
return packageHtmlErrors;
}
/**
* Loads the contents of a file in a String array.
* @return the lines in the file
* @param aFileName the name of the file to load
* @throws IOException error occurred
**/
private String[] getLines(String aFileName)
throws IOException
{
final LineNumberReader lnr =
new LineNumberReader(new FileReader(aFileName));
final ArrayList lines = new ArrayList();
while (true) {
final String l = lnr.readLine();
if (l == null) {
break;
}
lines.add(l);
}
return (String[]) lines.toArray(new String[0]);
}
/** notify all listeners about the audit start */
protected void fireAuditStarted()
{
final AuditEvent evt = new AuditEvent(this);
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
listener.auditStarted(evt);
}
}
/** notify all listeners about the audit end */
protected void fireAuditFinished()
{
final AuditEvent evt = new AuditEvent(this);
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
listener.auditFinished(evt);
}
}
/**
* notify all listeners about the beginning of a file audit
* @param aFileName the file to be audited
*/
protected void fireFileStarted(String aFileName)
{
final AuditEvent evt = new AuditEvent(this, aFileName);
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
listener.fileStarted(evt);
}
}
/**
* notify all listeners about the end of a file audit
* @param aFileName the audited file
*/
protected void fireFileFinished(String aFileName)
{
final AuditEvent evt = new AuditEvent(this, aFileName);
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
listener.fileFinished(evt);
}
}
/**
* notify all listeners about the errors in a file.
* @param aFileName the audited file
* @param aErrors the audit errors from the file
*/
protected void fireErrors(String aFileName, LineText[] aErrors)
{
for (int i = 0; i < aErrors.length; i++) {
final AuditEvent evt =
new AuditEvent(this, aFileName,
aErrors[i].getLineNo(),
aErrors[i].getColumnNo(),
aErrors[i].getText());
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
listener.addError(evt);
}
}
}
}
| false | true | private int process(String aFileName)
{
// check if already checked and passed the file
final File f = new File(aFileName);
final long timestamp = f.lastModified();
if (mCache.alreadyChecked(aFileName, timestamp)) {
return 0;
}
// Create a stripped down version
final String stripped;
if ((mConfig.getBasedir() == null)
|| !aFileName.startsWith(mConfig.getBasedir()))
{
stripped = aFileName;
}
else {
// making the assumption that there is text after basedir
stripped = aFileName.substring(mConfig.getBasedir().length() + 1);
}
LineText[] errors;
try {
fireFileStarted(stripped);
final String[] lines = getLines(aFileName);
try {
// try the 1.4 grammar first, this will succeed for
// all code that compiles without any warnings in JDK 1.4,
// that should cover most cases
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJava14Lexer jl = new GeneratedJava14Lexer(sar);
jl.setFilename(aFileName);
final GeneratedJava14Recognizer jr =
new SilentJava14Recognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
catch (RecognitionException re) {
// Parsing might have failed because the checked
// file contains "assert" as an identifier. Retry with a
// grammar that treats "assert" as an identifier
// and not as a keyword
// Arghh - the pain - duplicate code!
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJavaLexer jl = new GeneratedJavaLexer(sar);
jl.setFilename(aFileName);
final GeneratedJavaRecognizer jr =
new GeneratedJavaRecognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
errors = VerifierSingleton.getInstance().getMessages();
}
catch (FileNotFoundException fnfe) {
errors = new LineText[] {new LineText(0, "File not found!")};
}
catch (IOException ioe) {
errors = new LineText[] {
new LineText(0, "Got an IOException -" + ioe.getMessage())};
}
catch (RecognitionException re) {
errors = new LineText[] {
new LineText(0,
"Got a RecognitionException -" + re.getMessage())};
}
catch (TokenStreamException te) {
errors = new LineText[] {
new LineText(0,
"Got a TokenStreamException -" + te.getMessage())};
}
if (errors.length == 0) {
mCache.checkedOk(aFileName, timestamp);
}
else {
fireErrors(stripped, errors);
}
fireFileFinished(stripped);
return errors.length;
}
| private int process(String aFileName)
{
// check if already checked and passed the file
final File f = new File(aFileName);
final long timestamp = f.lastModified();
if (mCache.alreadyChecked(aFileName, timestamp)) {
return 0;
}
// Create a stripped down version
final String stripped;
final String basedir = mConfig.getBasedir();
if ((basedir == null) || !aFileName.startsWith(basedir)) {
stripped = aFileName;
}
else {
// making the assumption that there is text after basedir
final int skipSep = basedir.endsWith(File.separator) ? 0 : 1;
stripped = aFileName.substring(basedir.length() + skipSep);
}
LineText[] errors;
try {
fireFileStarted(stripped);
final String[] lines = getLines(aFileName);
try {
// try the 1.4 grammar first, this will succeed for
// all code that compiles without any warnings in JDK 1.4,
// that should cover most cases
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJava14Lexer jl = new GeneratedJava14Lexer(sar);
jl.setFilename(aFileName);
final GeneratedJava14Recognizer jr =
new SilentJava14Recognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
catch (RecognitionException re) {
// Parsing might have failed because the checked
// file contains "assert" as an identifier. Retry with a
// grammar that treats "assert" as an identifier
// and not as a keyword
// Arghh - the pain - duplicate code!
VerifierSingleton.getInstance().clearMessages();
VerifierSingleton.getInstance().setLines(lines);
final Reader sar = new StringArrayReader(lines);
final GeneratedJavaLexer jl = new GeneratedJavaLexer(sar);
jl.setFilename(aFileName);
final GeneratedJavaRecognizer jr =
new GeneratedJavaRecognizer(jl);
jr.setFilename(aFileName);
jr.setASTNodeClass(MyCommonAST.class.getName());
jr.compilationUnit();
}
errors = VerifierSingleton.getInstance().getMessages();
}
catch (FileNotFoundException fnfe) {
errors = new LineText[] {new LineText(0, "File not found!")};
}
catch (IOException ioe) {
errors = new LineText[] {
new LineText(0, "Got an IOException -" + ioe.getMessage())};
}
catch (RecognitionException re) {
errors = new LineText[] {
new LineText(0,
"Got a RecognitionException -" + re.getMessage())};
}
catch (TokenStreamException te) {
errors = new LineText[] {
new LineText(0,
"Got a TokenStreamException -" + te.getMessage())};
}
if (errors.length == 0) {
mCache.checkedOk(aFileName, timestamp);
}
else {
fireErrors(stripped, errors);
}
fireFileFinished(stripped);
return errors.length;
}
|
diff --git a/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java b/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
index e0e8f228..eb5d43a9 100755
--- a/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
+++ b/web/src/main/java/org/mule/galaxy/web/server/RegistryServiceImpl.java
@@ -1,1835 +1,1835 @@
/*
* $Id: ContextPathResolver.java 794 2008-04-23 22:23:10Z andrew $
* --------------------------------------------------------------------------------------
* 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 org.mule.galaxy.web.server;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.galaxy.Artifact;
import org.mule.galaxy.ArtifactType;
import org.mule.galaxy.ArtifactTypeDao;
import org.mule.galaxy.ArtifactVersion;
import org.mule.galaxy.DuplicateItemException;
import org.mule.galaxy.Entry;
import org.mule.galaxy.EntryResult;
import org.mule.galaxy.EntryVersion;
import org.mule.galaxy.Item;
import org.mule.galaxy.Link;
import org.mule.galaxy.Links;
import org.mule.galaxy.NotFoundException;
import org.mule.galaxy.PropertyException;
import org.mule.galaxy.PropertyInfo;
import org.mule.galaxy.Registry;
import org.mule.galaxy.RegistryException;
import org.mule.galaxy.Workspace;
import org.mule.galaxy.activity.Activity;
import org.mule.galaxy.activity.ActivityManager;
import org.mule.galaxy.activity.ActivityManager.EventType;
import org.mule.galaxy.collab.Comment;
import org.mule.galaxy.collab.CommentManager;
import org.mule.galaxy.event.EventManager;
import org.mule.galaxy.extension.Extension;
import org.mule.galaxy.impl.jcr.UserDetailsWrapper;
import org.mule.galaxy.index.Index;
import org.mule.galaxy.index.IndexManager;
import org.mule.galaxy.lifecycle.Lifecycle;
import org.mule.galaxy.lifecycle.LifecycleManager;
import org.mule.galaxy.lifecycle.Phase;
import org.mule.galaxy.policy.ApprovalMessage;
import org.mule.galaxy.policy.Policy;
import org.mule.galaxy.policy.PolicyException;
import org.mule.galaxy.policy.PolicyManager;
import org.mule.galaxy.query.OpRestriction;
import org.mule.galaxy.query.Query;
import org.mule.galaxy.query.QueryException;
import org.mule.galaxy.query.Restriction;
import org.mule.galaxy.query.SearchResults;
import org.mule.galaxy.query.OpRestriction.Operator;
import org.mule.galaxy.render.ItemRenderer;
import org.mule.galaxy.render.RendererManager;
import org.mule.galaxy.security.AccessControlManager;
import org.mule.galaxy.security.AccessException;
import org.mule.galaxy.security.Permission;
import org.mule.galaxy.security.User;
import org.mule.galaxy.security.UserManager;
import org.mule.galaxy.type.PropertyDescriptor;
import org.mule.galaxy.type.TypeManager;
import org.mule.galaxy.view.View;
import org.mule.galaxy.view.ArtifactViewManager;
import org.mule.galaxy.web.client.RPCException;
import org.mule.galaxy.web.rpc.EntryGroup;
import org.mule.galaxy.web.rpc.EntryVersionInfo;
import org.mule.galaxy.web.rpc.EntryInfo;
import org.mule.galaxy.web.rpc.ExtendedEntryInfo;
import org.mule.galaxy.web.rpc.ItemExistsException;
import org.mule.galaxy.web.rpc.ItemNotFoundException;
import org.mule.galaxy.web.rpc.LinkInfo;
import org.mule.galaxy.web.rpc.RegistryService;
import org.mule.galaxy.web.rpc.SearchPredicate;
import org.mule.galaxy.web.rpc.WActivity;
import org.mule.galaxy.web.rpc.WApprovalMessage;
import org.mule.galaxy.web.rpc.WPolicy;
import org.mule.galaxy.web.rpc.WArtifactType;
import org.mule.galaxy.web.rpc.WArtifactView;
import org.mule.galaxy.web.rpc.WComment;
import org.mule.galaxy.web.rpc.WExtensionInfo;
import org.mule.galaxy.web.rpc.WGovernanceInfo;
import org.mule.galaxy.web.rpc.WIndex;
import org.mule.galaxy.web.rpc.WLifecycle;
import org.mule.galaxy.web.rpc.WPhase;
import org.mule.galaxy.web.rpc.WPolicyException;
import org.mule.galaxy.web.rpc.WProperty;
import org.mule.galaxy.web.rpc.WPropertyDescriptor;
import org.mule.galaxy.web.rpc.WSearchResults;
import org.mule.galaxy.web.rpc.WUser;
import org.mule.galaxy.web.rpc.WWorkspace;
public class RegistryServiceImpl implements RegistryService {
protected static final String DEFAULT_DATETIME_FORMAT = "h:mm a, MMMM d, yyyy";
private static final String RECENT_VIEWS = "recent.artifactViews";
private final Log log = LogFactory.getLog(getClass());
private Registry registry;
private ArtifactTypeDao artifactTypeDao;
private RendererManager rendererManager;
private PolicyManager policyManager;
private IndexManager indexManager;
private ActivityManager activityManager;
private AccessControlManager accessControlManager;
private ArtifactViewManager artifactViewManager;
private TypeManager typeManager;
private UserManager userManager;
private ContextPathResolver contextPathResolver;
private LifecycleManager localLifecycleManager;
private EventManager eventManager;
public List<WExtensionInfo> getExtensions() throws RPCException {
ArrayList<WExtensionInfo> exts = new ArrayList<WExtensionInfo>();
for (Extension e : registry.getExtensions()) {
exts.add(new WExtensionInfo(e.getId(), e.getName(), e.getPropertyDescriptorConfigurationKeys(), e.isMultivalueSupported()));
}
return exts;
}
public Collection<WWorkspace> getWorkspaces() throws RPCException {
try {
Collection<Workspace> workspaces = registry.getWorkspaces();
List<WWorkspace> wis = new ArrayList<WWorkspace>();
for (Workspace w : workspaces) {
WWorkspace ww = toWeb(w);
wis.add(ww);
}
return wis;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private WWorkspace toWeb(Workspace w) {
WWorkspace ww = new WWorkspace(w.getId(), w.getName(), w.getPath());
ww.setDefaultLifecycleId(w.getDefaultLifecycle().getId());
Collection<Workspace> children = w.getWorkspaces();
if (children != null && children.size() > 0) {
ww.setWorkspaces(new ArrayList<WWorkspace>());
addWorkspaces(ww, children);
}
return ww;
}
private void addWorkspaces(WWorkspace parent, Collection<Workspace> workspaces) {
for (Workspace w : workspaces) {
WWorkspace ww = new WWorkspace(w.getId(), w.getName(), w.getPath());
parent.getWorkspaces().add(ww);
Collection<Workspace> children = w.getWorkspaces();
if (children != null && children.size() > 0) {
ww.setWorkspaces(new ArrayList<WWorkspace>());
addWorkspaces(ww, children);
}
}
}
public void addWorkspace(String parentWorkspaceId, String workspaceName, String lifecycleId) throws RPCException, ItemNotFoundException, ItemExistsException {
try {
Workspace w;
if (parentWorkspaceId == null || "[No parent]".equals(parentWorkspaceId)) {
w = registry.createWorkspace(workspaceName);
} else {
Workspace parent = (Workspace) registry.getItemById(parentWorkspaceId);
w = registry.createWorkspace(parent, workspaceName);
}
if (lifecycleId != null) {
w.setDefaultLifecycle(w.getLifecycleManager().getLifecycleById(lifecycleId));
registry.save(w);
}
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void updateWorkspace(String workspaceId, String parentWorkspaceId, String workspaceName, String lifecycleId)
throws RPCException, ItemNotFoundException {
try {
if (parentWorkspaceId == null || "[No parent]".equals(parentWorkspaceId)) {
parentWorkspaceId = null;
}
Workspace w = (Workspace) registry.getItemById(workspaceId);
if (lifecycleId != null) {
w.setDefaultLifecycle(w.getLifecycleManager().getLifecycleById(lifecycleId));
}
w.setName(workspaceName);
registry.save(w, parentWorkspaceId);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteWorkspace(String workspaceId) throws RPCException, ItemNotFoundException {
try {
registry.getItemById(workspaceId).delete();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public String newEntry(String workspaceId, String name, String version)
throws RPCException, ItemExistsException, WPolicyException, ItemNotFoundException {
try {
Workspace w = (Workspace) registry.getItemById(workspaceId);
EntryResult result = w.newEntry(name, version);
return result.getEntry().getId();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public String newEntryVersion(String entryId, String version)
throws RPCException, ItemExistsException, WPolicyException, ItemNotFoundException {
try {
Entry e = (Entry) registry.getItemById(entryId);
EntryResult result = e.newVersion(version);
return result.getEntryVersion().getId();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public Collection<WArtifactType> getArtifactTypes() {
Collection<ArtifactType> artifactTypes = artifactTypeDao.listAll();
List<WArtifactType> atis = new ArrayList<WArtifactType>();
for (ArtifactType a : artifactTypes) {
WArtifactType at = toWeb(a);
atis.add(at);
}
return atis;
}
public WArtifactType getArtifactType(String id) throws RPCException {
try {
return toWeb(artifactTypeDao.get(id));
} catch (Exception e) {
throw new RPCException(e.getMessage());
}
}
private WArtifactType toWeb(ArtifactType a) {
Set<QName> docTypes = a.getDocumentTypes();
List<String> docTypesAsStr = new ArrayList<String>();
if (docTypes != null) {
for (QName q : docTypes) {
docTypesAsStr.add(q.toString());
}
}
return new WArtifactType(a.getId(), a.getContentType(),
a.getDescription(), docTypesAsStr,
a.getFileExtensions());
}
public void deleteArtifactType(String id) throws RPCException {
try {
artifactTypeDao.delete(id);
} catch (RuntimeException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
}
}
public void saveArtifactType(WArtifactType artifactType) throws RPCException, ItemExistsException {
try {
ArtifactType at = fromWeb(artifactType);
artifactTypeDao.save(at);
} catch (RuntimeException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
private ArtifactType fromWeb(WArtifactType wat) {
ArtifactType at = new ArtifactType();
at.setId(wat.getId());
at.setDescription(wat.getDescription());
at.setContentType(wat.getMediaType());
at.setDocumentTypes(fromWeb(wat.getDocumentTypes()));
HashSet<String> exts = new HashSet<String>();
exts.addAll((Collection<String>) wat.getFileExtensions());
at.setFileExtensions(exts);
return at;
}
private Set<QName> fromWeb(Collection<String> documentTypes) {
if (documentTypes == null) return null;
Set<QName> s = new HashSet<QName>();
for (Object o : documentTypes) {
String qn = o.toString();
if (qn.startsWith("{}")) {
qn = qn.substring(2);
}
s.add(QName.valueOf(qn));
}
return s;
}
private OpRestriction getRestrictionForPredicate(SearchPredicate pred) {
String property = pred.getProperty();
String value = pred.getValue();
switch (pred.getMatchType()) {
case SearchPredicate.HAS_VALUE:
return OpRestriction.eq(property, value);
case SearchPredicate.LIKE:
return OpRestriction.like(property, value);
case SearchPredicate.DOES_NOT_HAVE_VALUE:
return OpRestriction.not(OpRestriction.eq(property, value));
default:
return null;
}
}
public WSearchResults getArtifacts(String workspaceId, String workspacePath, boolean includeChildWkspcs,
Set<String> artifactTypes, Set<SearchPredicate> searchPredicates, String freeformQuery,
int start, int maxResults) throws RPCException {
Query q = getQuery(searchPredicates, start, maxResults);
if (workspaceId != null) {
q.workspaceId(workspaceId, includeChildWkspcs);
} else if (workspacePath != null && !"".equals(workspacePath) && !"/".equals(workspacePath)) {
q.workspacePath(workspacePath, includeChildWkspcs);
}
try {
SearchResults results;
if (freeformQuery != null && !freeformQuery.equals(""))
results = registry.search(freeformQuery, start, maxResults);
else
results = registry.search(q);
return getSearchResults(artifactTypes, results);
} catch (QueryException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error("Could not query the registry.", e);
throw new RPCException(e.getMessage());
}
}
private Query getQuery(Set<SearchPredicate> searchPredicates, int start, int maxResults) {
Query q = new Query().orderBy("artifactType");
q.setMaxResults(maxResults);
q.setStart(start);
// Filter based on our search terms
if (searchPredicates != null) {
for (Object predObj : searchPredicates) {
SearchPredicate pred = (SearchPredicate) predObj;
q.add(getRestrictionForPredicate(pred));
}
}
return q;
}
private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
- && type != null
- && !artifactTypes.contains(type.getId())) {
+ && (type == null
+ || !artifactTypes.contains(type.getId()))) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
private EntryInfo createBasicEntryInfo(Entry a, ItemRenderer view) {
EntryInfo info = new EntryInfo();
return createBasicEntryInfo(a, view, info, false);
}
private EntryInfo createBasicEntryInfo(Entry a,
ItemRenderer view,
EntryInfo info,
boolean extended) {
info.setId(a.getId());
info.setWorkspaceId(a.getParent().getId());
info.setName(a.getName());
info.setPath(a.getParent().getPath());
int column = 0;
for (int i = 0; i < view.getColumnNames().length; i++) {
if (!extended && view.isSummary(i)) {
info.setColumn(column, view.getColumnValue(a, i));
column++;
} else if (extended && view.isDetail(i)) {
info.setColumn(column, view.getColumnValue(a, i));
column++;
}
}
return info;
}
public WSearchResults getArtifactsForView(String viewId,
int resultStart,
int maxResults)
throws RPCException {
View view = artifactViewManager.getArtifactView(viewId);
try {
return getSearchResults(null, registry.search(view.getQuery(), resultStart, maxResults));
} catch (QueryException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error("Could not query the registry.", e);
throw new RPCException(e.getMessage());
}
}
@SuppressWarnings("unchecked")
public void deleteArtifactView(String id) throws RPCException {
artifactViewManager.delete(id);
// clean up recent views too
User user = getCurrentUser();
List<String> views = (List<String>) user.getProperties().get(RECENT_VIEWS);
boolean wasFound = views.remove(id);
assert wasFound : "View deleted, but no corresponding Recent Views entry found for " + id;
}
public WArtifactView getArtifactView(String id) throws RPCException, ItemExistsException, ItemNotFoundException {
User user = getCurrentUser();
WArtifactView view = toWeb(artifactViewManager.getArtifactView(id));
try {
updateRecentArtifactViews(user, id);
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new ItemNotFoundException();
}
return view;
}
private void updateRecentArtifactViews(User user, String id) throws DuplicateItemException, NotFoundException {
List<String> recent = getRecentArtifactViewIds(user);
// remove this id if it alread exists
recent.remove(id);
// add the view to the top of the list
recent.add(0, id);
while (recent.size() > 5) {
recent.remove(recent.size() - 1);
}
userManager.save(user);
}
@SuppressWarnings("unchecked")
private List<String> getRecentArtifactViewIds(User user) {
if (user.getProperties() == null) {
user.setProperties(new HashMap<String, Object>());
}
List<String> recent = (List<String>) user.getProperties().get(RECENT_VIEWS);
if (recent == null) {
recent = new ArrayList<String>();
user.getProperties().put(RECENT_VIEWS, recent);
}
return recent;
}
public Collection<WArtifactView> getArtifactViews() throws RPCException {
List<WArtifactView> views = new ArrayList<WArtifactView>();
User currentUser = getCurrentUser();
for (View v : artifactViewManager.getArtifactViews(currentUser)) {
views.add(toWeb(v));
}
Collections.sort(views, new Comparator<WArtifactView>() {
public int compare(WArtifactView v1, WArtifactView v2) {
return v1.getName().compareTo(v2.getName());
}
});
return views;
}
public Collection<WArtifactView> getRecentArtifactViews() throws RPCException {
List<WArtifactView> views = new ArrayList<WArtifactView>();
User currentUser = getCurrentUser();
List<String> ids = getRecentArtifactViewIds(currentUser);
if (ids != null) {
for (String id : ids) {
views.add(toWeb(artifactViewManager.getArtifactView(id)));
}
}
return views;
}
private WArtifactView toWeb(View v) throws RPCException {
WArtifactView wv = new WArtifactView();
if (v == null) {
return wv;
}
wv.setName(v.getName());
wv.setId(v.getId());
try {
Query q = Query.fromString(v.getQuery());
wv.setPredicates(getPredicates(q));
wv.setShared(v.getUser() == null);
wv.setWorkspace(q.getWorkspacePath());
wv.setWorkspaceSearchRecursive(q.isWorkspaceSearchRecursive());
} catch (QueryException e) {
log.error("Could not parse query. " + e.getMessage(), e);
throw new RPCException(e.getMessage());
}
return wv;
}
/**
* Convert a string query to a set of search predicates for the SearchForm.
* You'll see that we do not have full fidelity yet between text queries and
* the actual form. However, that is not a problem as we'll only ever encounter
* queries which were created with the form. So there are some cases here
* that we don't have to worry about.
*
* @param q
* @return
* @throws RPCException
*/
public Set<SearchPredicate> getPredicates(Query q) throws RPCException {
Set<SearchPredicate> predicates = new HashSet<SearchPredicate>();
for (Restriction r : q.getRestrictions()) {
if (r instanceof OpRestriction) {
OpRestriction op = (OpRestriction) r;
Object left = op.getLeft();
Object right = op.getRight();
Operator operator = op.getOperator();
if (operator.equals(Operator.NOT)) {
if (right instanceof OpRestriction) {
OpRestriction op2 = (OpRestriction) right;
predicates.add(new SearchPredicate(op2.getLeft().toString(),
SearchPredicate.DOES_NOT_HAVE_VALUE,
op2.getRight().toString()));
} else {
throw new RPCException("Query could not be converted.");
}
} else if (operator.equals(Operator.EQUALS)) {
predicates.add(new SearchPredicate(left.toString(), SearchPredicate.HAS_VALUE, right.toString()));
} else if (operator.equals(Operator.LIKE)) {
predicates.add(new SearchPredicate(left.toString(), SearchPredicate.LIKE, right.toString()));
}
}
}
return predicates;
}
public String saveArtifactView(WArtifactView wv) throws RPCException {
View v = fromWeb(wv);
try {
artifactViewManager.save(v);
return v.getId();
} catch (DuplicateItemException e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save view.");
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
throw new RPCException("The view being saved has been deleted.");
}
}
private View fromWeb(WArtifactView wv) throws RPCException {
View v = new View();
v.setId(wv.getId());
v.setName(wv.getName());
if (!wv.isShared()) {
v.setUser(getCurrentUser());
}
Query query = getQuery(wv.getPredicates(), 0, 0);
query.workspacePath(wv.getWorkspace(), wv.isWorkspaceSearchRecursive());
v.setQuery(query.toString());
return v;
}
public Collection<WIndex> getIndexes() {
ArrayList<WIndex> windexes = new ArrayList<WIndex>();
Collection<Index> indices = indexManager.getIndexes();
for (Index idx : indices) {
windexes.add(toWeb(idx));
}
return windexes;
}
private WIndex toWeb(Index idx) {
ArrayList<String> docTypes = new ArrayList<String>();
if (idx.getDocumentTypes() != null) {
for (QName q : idx.getDocumentTypes()) {
docTypes.add(q.toString());
}
}
String qt;
if (String.class.equals(idx.getQueryType())) {
qt = "String";
} else {
qt = "QName";
}
return new WIndex(idx.getId(),
idx.getDescription(),
idx.getMediaType(),
idx.getConfiguration().get("property"),
idx.getConfiguration().get("expression"),
idx.getIndexer(),
qt,
docTypes);
}
public WIndex getIndex(String id) throws RPCException {
try {
Index idx = indexManager.getIndex(id);
if (idx == null) {
return null;
}
return toWeb(idx);
} catch (Exception e) {
throw new RPCException("Could not find index " + id);
}
}
public void saveIndex(WIndex wi) throws RPCException {
try {
Index idx = fromWeb(wi);
indexManager.save(idx);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save index.");
}
}
public void deleteIndex(String id, boolean removeArtifactMetadata) throws RPCException {
try {
indexManager.delete(id, removeArtifactMetadata);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Couldn't save index.");
}
}
private Index fromWeb(WIndex wi) throws RPCException {
Index idx = new Index();
idx.setId(wi.getId());
idx.setConfiguration(new HashMap<String, String>());
idx.setIndexer(wi.getIndexer());
if (idx.getIndexer().contains("Groovy")) {
idx.getConfiguration().put("script", wi.getExpression());
} else {
idx.getConfiguration().put("property", wi.getProperty());
idx.getConfiguration().put("expression", wi.getExpression());
}
idx.setIndexer(wi.getIndexer());
idx.setDescription(wi.getDescription());
idx.setMediaType(wi.getMediaType());
if (wi.getResultType().equals("String")) {
idx.setQueryType(String.class);
} else {
idx.setQueryType(QName.class);
}
Set<QName> docTypes = new HashSet<QName>();
for (Object o : wi.getDocumentTypes()) {
try {
docTypes.add(QName.valueOf(o.toString()));
} catch (IllegalArgumentException e) {
throw new RPCException("QName was formatted incorrectly: " + o.toString());
}
}
idx.setDocumentTypes(docTypes);
return idx;
}
public Collection<LinkInfo> getLinks(String itemId, String property) throws RPCException {
try {
Item item = registry.getItemById(itemId);
Links links = (Links) item.getProperty(property);
List<LinkInfo> deps = new ArrayList<LinkInfo>();
for (Link l : links.getLinks()) {
deps.add(toWeb(l, false));
}
for (Link l : links.getReciprocalLinks()) {
deps.add(toWeb(l, true));
}
return deps;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RPCException("Could not find artifact " + itemId);
}
}
private LinkInfo toWeb(Link l, boolean recip) {
Item i = recip ? l.getItem() : l.getLinkedTo();
String name;
int itemType;
String id = null;
if (i instanceof Entry) {
itemType = LinkInfo.TYPE_ENTRY;
name = ((Entry) i).getName();
id = i.getId();
} else if (i instanceof EntryVersion) {
itemType = LinkInfo.TYPE_ENTRY_VERSION;
EntryVersion av = ((EntryVersion) i);
name = av.getParent().getName() + " (" + av.getVersionLabel() + ")";
id = i.getId();
} else if (i == null) {
itemType = LinkInfo.TYPE_NOT_FOUND;
name = l.getLinkedToPath();
} else {
throw new UnsupportedOperationException();
}
return new LinkInfo(l.getId(),
l.isAutoDetected(),
id,
name,
itemType,
recip);
}
public ExtendedEntryInfo getEntry(String entryId) throws RPCException, ItemNotFoundException {
try {
Entry a = (Entry) registry.getItemById(entryId);
return getEntryGroup(a);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public ExtendedEntryInfo getArtifactByVersionId(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion av = registry.getArtifactVersion(artifactVersionId);
return getEntryGroup(av.getParent());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private ExtendedEntryInfo getEntryGroup(Entry e) {
ExtendedEntryInfo info = new ExtendedEntryInfo();
ItemRenderer view;
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
ArtifactType type = artifactTypeDao.getArtifactType(a.getContentType().toString(),
a.getDocumentType());
info.setType(type.getDescription());
info.setMediaType(type.getContentType().toString());
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
final String context = contextPathResolver.getContextPath();
info.setArtifactLink(getLink(context + "/api/registry", a));
info.setArtifactFeedLink(getLink(context + "/api/registry", a) + ";history");
info.setCommentsFeedLink(context + "/api/comments");
} else {
view = rendererManager.getArtifactRenderer("application/octet-stream");
info.setType("Entry");
}
createBasicEntryInfo(e, view, info, true);
info.setDescription(e.getDescription());
List<WComment> wcs = info.getComments();
Workspace workspace = (Workspace) e.getParent();
List<Comment> comments = workspace.getCommentManager().getComments(e.getId());
for (Comment c : comments) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
WComment wc = new WComment(c.getId(), c.getUser().getUsername(), dateFormat.format(c
.getDate().getTime()), c.getText());
wcs.add(wc);
Set<Comment> children = c.getComments();
if (children != null && children.size() > 0) {
addComments(wc, children);
}
}
List<EntryVersionInfo> versions = new ArrayList<EntryVersionInfo>();
for (EntryVersion av : e.getVersions()) {
versions.add(toWeb((EntryVersion)av, false));
}
info.setVersions(versions);
return info;
}
public EntryVersionInfo getEntryVersionInfo(String entryVersionId, boolean showHidden) throws RPCException,
ItemNotFoundException {
try {
EntryVersion ev = (EntryVersion) registry.getItemById(entryVersionId);
return toWeb(ev, showHidden);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
@SuppressWarnings("unchecked")
private EntryVersionInfo toWeb(EntryVersion av, boolean showHidden) {
EntryVersionInfo vi = new EntryVersionInfo(av.getId(),
av.getVersionLabel(),
av.getCreated().getTime(),
av.isDefault(),
av.isEnabled(),
av.getAuthor().getName(),
av.getAuthor().getUsername(),
av.isIndexedPropertiesStale());
if (av instanceof ArtifactVersion) {
vi.setLink(getVersionLink((ArtifactVersion)av));
}
for (Iterator<PropertyInfo> props = av.getProperties(); props.hasNext();) {
PropertyInfo p = props.next();
if (!showHidden && !p.isVisible()) {
continue;
}
Object val = p.getInternalValue();
val = convertQNames(val);
String desc = p.getDescription();
if (desc == null) {
desc = p.getName();
}
PropertyDescriptor pd = p.getPropertyDescriptor();
String ext = pd != null && pd.getExtension() != null ? pd.getExtension().getId() : null;
vi.getProperties().add(new WProperty(p.getName(), desc, val, ext, p.isLocked()));
}
Collections.sort(vi.getProperties(), new Comparator() {
public int compare(Object o1, Object o2) {
return ((WProperty) o1).getDescription().compareTo(((WProperty) o2).getDescription());
}
});
return vi;
}
/**
* This method is here temporarily until we can serialize qnames remotely
* @param val
*/
private Object convertQNames(Object val) {
if (val instanceof Collection) {
List<String> objs = new ArrayList<String>();
for (Object o : (Collection) val) {
objs.add(o.toString());
}
return objs;
}
return val;
}
private String getLink(String base, Artifact a) {
StringBuilder sb = new StringBuilder();
Workspace w = (Workspace) a.getParent();
sb.append(base).append(w.getPath()).append(a.getName());
return sb.toString();
}
public WComment addComment(String entryId, String parentComment, String text) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
Comment comment = new Comment();
comment.setText(text);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
comment.setDate(cal);
comment.setUser(getCurrentUser());
Workspace w = (Workspace)artifact.getParent();
CommentManager commentManager = w.getCommentManager();
if (parentComment != null) {
Comment c = commentManager.getComment(parentComment);
if (c == null) {
throw new RPCException("Invalid parent comment");
}
comment.setParent(c);
} else {
comment.setItem(artifact);
}
commentManager.addComment(comment);
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
return new WComment(comment.getId(), comment.getUser().getUsername(), dateFormat.format(comment
.getDate().getTime()), comment.getText());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private User getCurrentUser() throws RPCException {
UserDetailsWrapper wrapper = (UserDetailsWrapper) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (wrapper == null) {
throw new RPCException("No user is logged in!");
}
return wrapper.getUser();
}
private void addComments(WComment parent, Set<Comment> comments) {
for (Comment c : comments) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
WComment child = new WComment(c.getId(), c.getUser().getUsername(), dateFormat.format(c.getDate()
.getTime()), c.getText());
parent.getComments().add(child);
Set<Comment> children = c.getComments();
if (children != null && children.size() > 0) {
addComments(child, children);
}
}
}
public void setProperty(String entryId, String propertyName, Collection<String> propertyValue)
throws RPCException, ItemNotFoundException, WPolicyException {
setProperty(entryId, propertyName, (Object)propertyValue);
}
public void setProperty(String entryId, String propertyName, String propertyValue)
throws RPCException, ItemNotFoundException, WPolicyException {
setProperty(entryId, propertyName, (Object)propertyValue);
}
protected void setProperty(String itemId, String propertyName, Object propertyValue) throws RPCException, ItemNotFoundException, WPolicyException {
try {
Item item = registry.getItemById(itemId);
item.setInternalProperty(propertyName, propertyValue);
registry.save(item);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PropertyException e) {
// occurs if property name is formatted wrong
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public void setProperty(Collection<String> entryIds, String propertyName, Collection<String> propertyValue)
throws RPCException, ItemNotFoundException {
}
public void setProperty(Collection<String> entryIds, String propertyName, String propertyValue)
throws RPCException, ItemNotFoundException {
}
public void setProperty(Collection<String> entryIds, String propertyName, Object propertyValue) throws RPCException, ItemNotFoundException {
}
public void deleteProperty(String itemId, String propertyName) throws RPCException, ItemNotFoundException {
try {
Item item = registry.getItemById(itemId);
item.setProperty(propertyName, null);
registry.save(item);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PropertyException e) {
// occurs if property name is formatted wrong
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteProperty(Collection<String> entryIds, String propertyName) throws RPCException, ItemNotFoundException {
}
public void deletePropertyDescriptor(String id) throws RPCException {
typeManager.deletePropertyDescriptor(id);
}
public WPropertyDescriptor getPropertyDescriptor(String id) throws RPCException, ItemNotFoundException {
try {
return toWeb(typeManager.getPropertyDescriptor(id));
} catch (NotFoundException e) {
throw new ItemNotFoundException();
}
}
public List<WPropertyDescriptor> getPropertyDescriptors(boolean includeIndex) throws RPCException {
List<WPropertyDescriptor> pds = new ArrayList<WPropertyDescriptor>();
for (PropertyDescriptor pd : typeManager.getPropertyDescriptors(includeIndex)) {
pds.add(toWeb(pd));
}
return pds;
}
private WPropertyDescriptor toWeb(PropertyDescriptor pd) {
String ext = pd.getExtension() != null ? pd.getExtension().getId() : null;
return new WPropertyDescriptor(pd.getId(), pd.getProperty(), pd.getDescription(), ext, pd.isMultivalued(), pd.getConfiguration());
}
public void savePropertyDescriptor(WPropertyDescriptor wpd) throws RPCException, ItemNotFoundException, ItemExistsException {
try {
PropertyDescriptor pd;
if (wpd.getId() == null) {
pd = new PropertyDescriptor();
} else {
pd = typeManager.getPropertyDescriptor(wpd.getId());
}
pd.setProperty(wpd.getName());
pd.setDescription(wpd.getDescription());
pd.setMultivalued(wpd.isMultiValued());
pd.setConfiguration(wpd.getConfiguration());
pd.setExtension(registry.getExtension(wpd.getExtension()));
typeManager.savePropertyDescriptor(pd);
wpd.setId(pd.getId());
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void setDescription(String entryId, String description) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
artifact.setDescription(description);
registry.save(artifact);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void move(String entryId, String workspaceId, String name) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
registry.move(artifact, workspaceId, name);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public void delete(String entryId) throws RPCException, ItemNotFoundException {
try {
Artifact artifact = registry.getArtifact(entryId);
artifact.delete();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public boolean deleteArtifactVersion(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion av = registry.getArtifactVersion(artifactVersionId);
Artifact a = (Artifact) av.getParent();
boolean last = a.getVersions().size() == 1;
av.delete();
return last;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
public WGovernanceInfo getGovernanceInfo(String artifactVersionId) throws RPCException, ItemNotFoundException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
WGovernanceInfo gov = new WGovernanceInfo();
Phase phase = (Phase) artifact.getProperty(Registry.PRIMARY_LIFECYCLE);
gov.setCurrentPhase(phase.getName());
gov.setLifecycle(phase.getLifecycle().getName());
gov.setNextPhases(toWeb(phase.getNextPhases()));
gov.setPreviousPhases(toWeb(phase.getPreviousPhases()));
// Collection<PolicyInfo> policies =
// policyManager.getActivePolicies(artifact, false);
return gov;
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private List<WPhase> toWeb(Set<Phase> nextPhases) {
List<WPhase> wNextPhases = new ArrayList<WPhase>();
for (Phase p : nextPhases) {
wNextPhases.add(toWeb(p));
}
return wNextPhases;
}
// TODO:
public void transition(Collection<String> entryIds, String lifecycle, String phase) throws RPCException, ItemNotFoundException {
}
public Collection<WLifecycle> getLifecycles() throws RPCException {
Collection<Lifecycle> lifecycles = localLifecycleManager.getLifecycles();
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
ArrayList<WLifecycle> wls = new ArrayList<WLifecycle>();
for (Lifecycle l : lifecycles) {
WLifecycle lifecycle = toWeb(l, defaultLifecycle.equals(l));
wls.add(lifecycle);
}
return wls;
}
public WLifecycle getLifecycle(String id) throws RPCException {
try {
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
Lifecycle l = localLifecycleManager.getLifecycleById(id);
return toWeb(l, defaultLifecycle.equals(l));
} catch (Exception e) {
throw new RPCException(e.getMessage());
}
}
private WLifecycle toWeb(Lifecycle l, boolean defaultLifecycle) {
WLifecycle lifecycle = new WLifecycle(l.getId(), l.getName(), defaultLifecycle);
List<WPhase> wphases = new ArrayList<WPhase>();
lifecycle.setPhases(wphases);
for (Phase p : l.getPhases().values()) {
WPhase wp = toWeb(p);
wphases.add(wp);
if (p.equals(l.getInitialPhase())) {
lifecycle.setInitialPhase(wp);
}
}
for (Phase p : l.getPhases().values()) {
WPhase wp = lifecycle.getPhase(p.getName());
List<WPhase> nextPhases = new ArrayList<WPhase>();
for (Phase next : p.getNextPhases()) {
WPhase wnext = lifecycle.getPhase(next.getName());
nextPhases.add(wnext);
}
wp.setNextPhases(nextPhases);
}
Collections.sort(wphases, new Comparator<WPhase>() {
public int compare(WPhase o1, WPhase o2) {
return o1.getName().compareTo(o2.getName());
}
});
return lifecycle;
}
private WPhase toWeb(Phase p) {
WPhase wp = new WPhase(p.getId(), p.getName());
return wp;
}
public Collection<String> getActivePoliciesForLifecycle(String lifecycleName, String workspaceId)
throws RPCException {
Collection<Policy> pols = null;
Lifecycle lifecycle = localLifecycleManager.getLifecycle(lifecycleName);
try {
if (workspaceId != null) {
Workspace w = (Workspace) registry.getItemById(workspaceId);
pols = policyManager.getActivePolicies(w, lifecycle);
} else {
pols = policyManager.getActivePolicies(lifecycle);
}
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
return getArtifactPolicyIds(pols);
}
public Collection<String> getActivePoliciesForPhase(String lifecycle, String phaseName, String workspaceId)
throws RPCException {
Collection<Policy> pols = null;
Phase phase = localLifecycleManager.getLifecycle(lifecycle).getPhase(phaseName);
try {
if (workspaceId != null) {
Workspace w = (Workspace) registry.getItemById(workspaceId);
pols = policyManager.getActivePolicies(w, phase);
} else {
pols = policyManager.getActivePolicies(phase);
}
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
return getArtifactPolicyIds(pols);
}
public void setActivePolicies(String workspace, String lifecycle, String phase, Collection<String> ids)
throws RPCException, WPolicyException, ItemNotFoundException {
Lifecycle l = localLifecycleManager.getLifecycle(lifecycle);
List<Policy> policies = getArtifactPolicies(ids);
try {
if (phase != null) {
Phase p = l.getPhase(phase);
if (p == null) {
throw new RPCException("Invalid phase: " + phase);
}
List<Phase> phases = Arrays.asList(p);
if (workspace == null || "".equals(workspace)) {
policyManager.setActivePolicies(phases, policies.toArray(new Policy[policies
.size()]));
} else {
Workspace w = (Workspace) registry.getItemById(workspace);
policyManager.setActivePolicies(w, phases, policies.toArray(new Policy[policies
.size()]));
}
} else {
if (workspace == null || "".equals(workspace)) {
policyManager.setActivePolicies(l, policies.toArray(new Policy[policies.size()]));
} else {
Workspace w = (Workspace) registry.getItemById(workspace);
policyManager.setActivePolicies(w, l, policies
.toArray(new Policy[policies.size()]));
}
}
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
private WPolicyException toWeb(PolicyException e) {
Map<EntryInfo, Collection<WApprovalMessage>> failures = new HashMap<EntryInfo, Collection<WApprovalMessage>>();
for (Map.Entry<Item, List<ApprovalMessage>> entry : e.getPolicyFailures().entrySet()) {
Item i = entry.getKey();
List<ApprovalMessage> approvals = entry.getValue();
Artifact a = (Artifact) i.getParent();
ItemRenderer view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
EntryInfo info = createBasicEntryInfo(a, view);
ArrayList<WApprovalMessage> wapprovals = new ArrayList<WApprovalMessage>();
for (ApprovalMessage app : approvals) {
wapprovals.add(new WApprovalMessage(app.getMessage(), app.isWarning()));
}
failures.put(info, wapprovals);
}
WPolicyException e2 = new WPolicyException(failures);
return e2;
}
private List<Policy> getArtifactPolicies(Collection ids) {
List<Policy> policies = new ArrayList<Policy>();
for (Iterator itr = ids.iterator(); itr.hasNext();) {
String id = (String) itr.next();
Policy policy = policyManager.getPolicy(id);
policies.add(policy);
}
return policies;
}
private Collection<String> getArtifactPolicyIds(Collection<Policy> pols) {
ArrayList<String> polNames = new ArrayList<String>();
for (Policy ap : pols) {
polNames.add(ap.getId());
}
return polNames;
}
public void setDefault(String artifactVersionId) throws RPCException, ItemNotFoundException, WPolicyException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
artifact.setAsDefaultVersion();
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public void setEnabled(String artifactVersionId, boolean enabled) throws RPCException, ItemNotFoundException, WPolicyException {
try {
ArtifactVersion artifact = registry.getArtifactVersion(artifactVersionId);
artifact.setEnabled(enabled);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new RPCException(e.getMessage());
} catch (NotFoundException e) {
throw new ItemNotFoundException();
} catch (AccessException e) {
throw new RPCException(e.getMessage());
} catch (PolicyException e) {
throw toWeb(e);
}
}
public Collection<WPolicy> getPolicies() throws RPCException {
Collection<Policy> policies = policyManager.getPolicies();
List<WPolicy> gwtPolicies = new ArrayList<WPolicy>();
for (Policy p : policies) {
gwtPolicies.add(toWeb(p));
}
Collections.sort(gwtPolicies, new Comparator<WPolicy>() {
public int compare(WPolicy o1, WPolicy o2) {
return o1.getName().compareTo(o2.getName());
}
});
return gwtPolicies;
}
public void saveLifecycle(WLifecycle wl) throws RPCException, ItemExistsException {
Lifecycle l = fromWeb(wl);
try {
localLifecycleManager.save(l);
if (wl.isDefaultLifecycle()) {
Lifecycle defaultLifecycle = localLifecycleManager.getDefaultLifecycle();
if (!defaultLifecycle.equals(l)) {
localLifecycleManager.setDefaultLifecycle(l);
}
}
} catch (DuplicateItemException e) {
throw new ItemExistsException();
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
public void deleteLifecycle(String id) throws RPCException {
try {
String fallback = localLifecycleManager.getDefaultLifecycle().getId();
if (id.equals(fallback)) {
throw new RPCException("The default lifecycle cannot be deleted. Please assign " +
"another lifecycle to be the default before deleting this one.");
}
localLifecycleManager.delete(id, fallback);
} catch (NotFoundException e) {
throw new RPCException(e.getMessage());
}
}
private Lifecycle fromWeb(WLifecycle wl) throws RPCException {
Lifecycle l = new Lifecycle();
l.setPhases(new HashMap<String, Phase>());
l.setName(wl.getName());
l.setId(wl.getId());
for (Object o : wl.getPhases()) {
WPhase wp = (WPhase) o;
Phase p = new Phase(l);
p.setId(wp.getId());
p.setName(wp.getName());
l.getPhases().put(p.getName(), p);
}
for (Object o : wl.getPhases()) {
WPhase wp = (WPhase) o;
Phase p = l.getPhase(wp.getName());
p.setNextPhases(new HashSet<Phase>());
if (wp.getNextPhases() != null) {
for (Object oNext : wp.getNextPhases()) {
WPhase wNext = (WPhase) oNext;
Phase next = l.getPhase(wNext.getName());
p.getNextPhases().add(next);
}
}
}
if (wl.getInitialPhase() == null) {
throw new RPCException("You must set a phase as the initial phase.");
}
l.setInitialPhase(l.getPhase(wl.getInitialPhase().getName()));
return l;
}
private WPolicy toWeb(Policy p) {
WPolicy wap = new WPolicy();
wap.setId(p.getId());
wap.setDescription(p.getDescription());
wap.setName(p.getName());
return wap;
}
private String getVersionLink(ArtifactVersion av) {
Artifact a = (Artifact) av.getParent();
StringBuilder sb = new StringBuilder();
Workspace w = (Workspace) a.getParent();
final String context = contextPathResolver.getContextPath();
sb.append(context).append("/api/registry").append(w.getPath()).append(a.getName()).append("?version=")
.append(av.getVersionLabel());
return sb.toString();
}
public Collection<WActivity> getActivities(Date from, Date to, String user, String eventTypeStr, int start,
int results, boolean ascending) throws RPCException {
if ("All".equals(user)) {
user = null;
}
if (from != null) {
Calendar c = Calendar.getInstance();
c.setTime(from);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
from = c.getTime();
}
if (to != null) {
Calendar c = Calendar.getInstance();
c.setTime(to);
c.set(Calendar.HOUR, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
to = c.getTime();
}
EventType eventType = null;
if ("Info".equals(eventTypeStr)) {
eventType = EventType.INFO;
} else if ("Warning".equals(eventTypeStr)) {
eventType = EventType.WARNING;
} else if ("Error".equals(eventTypeStr)) {
eventType = EventType.ERROR;
}
try {
Collection<Activity> activities = activityManager.getActivities(from, to, user, eventType, start,
results, ascending);
ArrayList<WActivity> wactivities = new ArrayList<WActivity>();
for (Activity a : activities) {
wactivities.add(createWActivity(a));
}
return wactivities;
} catch (AccessException e) {
throw new RPCException(e.getMessage());
}
}
protected WActivity createWActivity(Activity a) {
WActivity wa = new WActivity();
wa.setId(a.getId());
wa.setEventType(a.getEventType().getText());
if (a.getUser() != null) {
wa.setUsername(a.getUser().getUsername());
wa.setName(a.getUser().getName());
}
wa.setMessage(a.getMessage());
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
wa.setDate(dateFormat.format(a.getDate().getTime()));
return wa;
}
public WUser getUserInfo() throws RPCException {
User user = getCurrentUser();
WUser w = SecurityServiceImpl.createWUser(user);
List<String> perms = new ArrayList<String>();
for (Permission p : accessControlManager.getGrantedPermissions(user)) {
perms.add(p.toString());
}
w.setPermissions(perms);
return w;
}
public void setAccessControlManager(AccessControlManager accessControlManager) {
this.accessControlManager = accessControlManager;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
public void setTypeManager(TypeManager typeManager) {
this.typeManager = typeManager;
}
public void setLifecycleManager(LifecycleManager lifecycleManager) {
this.localLifecycleManager = lifecycleManager;
}
public void setArtifactTypeDao(ArtifactTypeDao artifactTypeDao) {
this.artifactTypeDao = artifactTypeDao;
}
public void setPolicyManager(PolicyManager policyManager) {
this.policyManager = policyManager;
}
public void setRendererManager(RendererManager viewManager) {
this.rendererManager = viewManager;
}
public void setActivityManager(ActivityManager activityManager) {
this.activityManager = activityManager;
}
public void setIndexManager(IndexManager indexManager) {
this.indexManager = indexManager;
}
public void setArtifactViewManager(ArtifactViewManager artifactViewManager) {
this.artifactViewManager = artifactViewManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public ContextPathResolver getContextPathResolver() {
return contextPathResolver;
}
public void setContextPathResolver(final ContextPathResolver contextPathResolver) {
this.contextPathResolver = contextPathResolver;
}
public EventManager getEventManager() {
return eventManager;
}
public void setEventManager(final EventManager eventManager) {
this.eventManager = eventManager;
}
}
| true | true | private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
&& type != null
&& !artifactTypes.contains(type.getId())) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
| private WSearchResults getSearchResults(Set<String> artifactTypes, SearchResults results) {
Map<String, EntryGroup> name2group = new HashMap<String, EntryGroup>();
Map<String, ItemRenderer> name2view = new HashMap<String, ItemRenderer>();
int total = 0;
for (Object obj : results.getResults()) {
Entry e = (Entry) obj;
String groupName;
ArtifactType type = null;
if (e instanceof Artifact) {
type = artifactTypeDao.getArtifactType(
((Artifact) e).getContentType().toString(),
((Artifact) e).getDocumentType());
groupName = type.getDescription();
} else {
groupName = "Entries";
}
// If we want to filter based on the artifact type, filter!
if (artifactTypes != null && artifactTypes.size() != 0
&& (type == null
|| !artifactTypes.contains(type.getId()))) {
continue;
}
total++;
EntryGroup g = name2group.get(groupName);
ItemRenderer view = name2view.get(groupName);
if (g == null) {
g = new EntryGroup();
g.setName(groupName);
name2group.put(groupName, g);
if (e instanceof Artifact) {
Artifact a = (Artifact) e;
view = rendererManager.getArtifactRenderer(a.getDocumentType());
if (view == null) {
view = rendererManager.getArtifactRenderer(a.getContentType().toString());
}
} else {
// Hack
view = rendererManager.getArtifactRenderer("application/octet-stream");
}
name2view.put(groupName, view);
int i = 0;
for (String col : view.getColumnNames()) {
if (view.isSummary(i)) {
g.getColumns().add(col);
}
i++;
}
}
EntryInfo info = createBasicEntryInfo(e, view);
g.getRows().add(info);
}
List<EntryGroup> values = new ArrayList<EntryGroup>();
List<String> keys = new ArrayList<String>();
keys.addAll(name2group.keySet());
Collections.sort(keys);
for (String key : keys) {
values.add(name2group.get(key));
}
WSearchResults wsr = new WSearchResults();
wsr.setResults(values);
wsr.setTotal(total);
return wsr;
}
|
diff --git a/src/com/oux/SmartGPSLogger/IntentReceiver.java b/src/com/oux/SmartGPSLogger/IntentReceiver.java
index 1394529..e7d9edf 100644
--- a/src/com/oux/SmartGPSLogger/IntentReceiver.java
+++ b/src/com/oux/SmartGPSLogger/IntentReceiver.java
@@ -1,61 +1,61 @@
/*
* Copyright (C) 2012 Jérémy Compostella
*
* 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.oux.SmartGPSLogger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.IBinder;
import android.util.Log;
import android.os.PowerManager;
public class IntentReceiver extends BroadcastReceiver {
private static final String TAG = "IntentReceiver";
private static PowerManager.WakeLock wakelock;
public static final String REQUEST_NEW_LOCATION = "com.oux.REQUEST_NEW_LOCATION";
public static final String NEW_LOCATION_REQUESTED = "com.oux.NEW_LOCATION_REQUESTED";
@Override
public void onReceive(Context context, Intent intent) {
Log.d("IntentReceiver", "intent received : " + intent.getAction());
if (wakelock == null) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"GPSIntentReceiver");
}
- if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()) ||
+ if ("android.intent.action.MEDIA_MOUNTED".equals(intent.getAction()) ||
REQUEST_NEW_LOCATION.equals(intent.getAction())) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
if (pref.getBoolean("onboot",true)) {
Intent service = new Intent(context, GPSService.class);
context.startService(new Intent(context, GPSService.class));
if (!wakelock.isHeld())
wakelock.acquire();
}
} else if (NEW_LOCATION_REQUESTED.equals(intent.getAction()))
if (wakelock.isHeld())
wakelock.release();
}
}
// vi:et
| true | true | public void onReceive(Context context, Intent intent) {
Log.d("IntentReceiver", "intent received : " + intent.getAction());
if (wakelock == null) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"GPSIntentReceiver");
}
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()) ||
REQUEST_NEW_LOCATION.equals(intent.getAction())) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
if (pref.getBoolean("onboot",true)) {
Intent service = new Intent(context, GPSService.class);
context.startService(new Intent(context, GPSService.class));
if (!wakelock.isHeld())
wakelock.acquire();
}
} else if (NEW_LOCATION_REQUESTED.equals(intent.getAction()))
if (wakelock.isHeld())
wakelock.release();
}
| public void onReceive(Context context, Intent intent) {
Log.d("IntentReceiver", "intent received : " + intent.getAction());
if (wakelock == null) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"GPSIntentReceiver");
}
if ("android.intent.action.MEDIA_MOUNTED".equals(intent.getAction()) ||
REQUEST_NEW_LOCATION.equals(intent.getAction())) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
if (pref.getBoolean("onboot",true)) {
Intent service = new Intent(context, GPSService.class);
context.startService(new Intent(context, GPSService.class));
if (!wakelock.isHeld())
wakelock.acquire();
}
} else if (NEW_LOCATION_REQUESTED.equals(intent.getAction()))
if (wakelock.isHeld())
wakelock.release();
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperEngine.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperEngine.java
index 21aaeffba..2308e1759 100755
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperEngine.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperEngine.java
@@ -1,830 +1,833 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* 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.broadinstitute.sting.gatk.walkers.genotyper;
import com.google.java.contract.Requires;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.commandline.RodBinding;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.AlignmentContextUtils;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.annotator.VariantAnnotatorEngine;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.baq.BAQ;
import org.broadinstitute.sting.utils.codecs.vcf.VCFConstants;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.pileup.PileupElement;
import org.broadinstitute.sting.utils.pileup.ReadBackedExtendedEventPileup;
import org.broadinstitute.sting.utils.pileup.ReadBackedPileup;
import org.broadinstitute.sting.utils.variantcontext.*;
import java.io.PrintStream;
import java.util.*;
public class UnifiedGenotyperEngine {
public static final String LOW_QUAL_FILTER_NAME = "LowQual";
public enum OUTPUT_MODE {
/** produces calls only at variant sites */
EMIT_VARIANTS_ONLY,
/** produces calls at variant sites and confident reference sites */
EMIT_ALL_CONFIDENT_SITES,
/** produces calls at any callable site regardless of confidence; this argument is intended for point
* mutations (SNPs) only and while some indel calls may be produced they are by no means comprehensive */
EMIT_ALL_SITES
}
protected static final List<Allele> NO_CALL_ALLELES = Arrays.asList(Allele.NO_CALL, Allele.NO_CALL);
protected static final double SUM_GL_THRESH_NOCALL = -0.001; // if sum(gl) is bigger than this threshold, we treat GL's as non-informative and will force a no-call.
// the unified argument collection
private final UnifiedArgumentCollection UAC;
public UnifiedArgumentCollection getUAC() { return UAC; }
// the annotation engine
private final VariantAnnotatorEngine annotationEngine;
// the model used for calculating genotypes
private ThreadLocal<Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>> glcm = new ThreadLocal<Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>>();
// the model used for calculating p(non-ref)
private ThreadLocal<AlleleFrequencyCalculationModel> afcm = new ThreadLocal<AlleleFrequencyCalculationModel>();
// because the allele frequency priors are constant for a given i, we cache the results to avoid having to recompute everything
private final double[][] log10AlleleFrequencyPriorsSNPs;
private final double[][] log10AlleleFrequencyPriorsIndels;
// the allele frequency likelihoods (allocated once as an optimization)
private ThreadLocal<double[][]> log10AlleleFrequencyLikelihoods = new ThreadLocal<double[][]>();
private ThreadLocal<double[][]> log10AlleleFrequencyPosteriors = new ThreadLocal<double[][]>();
// the priors object
private final GenotypePriors genotypePriorsSNPs;
private final GenotypePriors genotypePriorsIndels;
// samples in input
private final Set<String> samples;
// the various loggers and writers
private final Logger logger;
private final PrintStream verboseWriter;
// number of chromosomes (2 * samples) in input
private final int N;
// the standard filter to use for calls below the confidence threshold but above the emit threshold
private static final Set<String> filter = new HashSet<String>(1);
private final GenomeLocParser genomeLocParser;
private final boolean BAQEnabledOnCMDLine;
// ---------------------------------------------------------------------------------------------------------
//
// Public interface functions
//
// ---------------------------------------------------------------------------------------------------------
@Requires({"toolkit != null", "UAC != null"})
public UnifiedGenotyperEngine(GenomeAnalysisEngine toolkit, UnifiedArgumentCollection UAC) {
this(toolkit, UAC, Logger.getLogger(UnifiedGenotyperEngine.class), null, null, SampleUtils.getSAMFileSamples(toolkit.getSAMFileHeader()));
}
@Requires({"toolkit != null", "UAC != null", "logger != null", "samples != null && samples.size() > 0"})
public UnifiedGenotyperEngine(GenomeAnalysisEngine toolkit, UnifiedArgumentCollection UAC, Logger logger, PrintStream verboseWriter, VariantAnnotatorEngine engine, Set<String> samples) {
this.BAQEnabledOnCMDLine = toolkit.getArguments().BAQMode != BAQ.CalculationMode.OFF;
genomeLocParser = toolkit.getGenomeLocParser();
this.samples = new TreeSet<String>(samples);
// note that, because we cap the base quality by the mapping quality, minMQ cannot be less than minBQ
this.UAC = UAC.clone();
this.logger = logger;
this.verboseWriter = verboseWriter;
this.annotationEngine = engine;
N = 2 * this.samples.size();
log10AlleleFrequencyPriorsSNPs = new double[UAC.MAX_ALTERNATE_ALLELES][N+1];
log10AlleleFrequencyPriorsIndels = new double[UAC.MAX_ALTERNATE_ALLELES][N+1];
computeAlleleFrequencyPriors(N, log10AlleleFrequencyPriorsSNPs, UAC.heterozygosity);
computeAlleleFrequencyPriors(N, log10AlleleFrequencyPriorsIndels, UAC.INDEL_HETEROZYGOSITY);
genotypePriorsSNPs = createGenotypePriors(GenotypeLikelihoodsCalculationModel.Model.SNP);
genotypePriorsIndels = createGenotypePriors(GenotypeLikelihoodsCalculationModel.Model.INDEL);
filter.add(LOW_QUAL_FILTER_NAME);
}
/**
* Compute full calls at a given locus. Entry point for engine calls from the UnifiedGenotyper.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @return the VariantCallContext object
*/
public VariantCallContext calculateLikelihoodsAndGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext) {
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel(tracker, refContext, rawContext );
if( model == null ) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ? generateEmptyContext(tracker, refContext, null, rawContext) : null);
}
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
if ( stratifiedContexts == null ) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ? generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext) : null);
}
VariantContext vc = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, null, true, model);
if ( vc == null )
return null;
return calculateGenotypes(tracker, refContext, rawContext, stratifiedContexts, vc, model);
}
/**
* Compute GLs at a given locus. Entry point for engine calls from UGCalcLikelihoods.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @return the VariantContext object
*/
public VariantContext calculateLikelihoods(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext) {
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel( tracker, refContext, rawContext );
if( model == null )
return null;
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
if ( stratifiedContexts == null )
return null;
return calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, null, true, model);
}
/**
* Compute genotypes at a given locus. Entry point for engine calls from UGCallVariants.
*
* @param tracker the meta data tracker
* @param refContext the reference base
* @param rawContext contextual information around the locus
* @param vc the GL-annotated variant context
* @return the VariantCallContext object
*/
public VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, VariantContext vc) {
final GenotypeLikelihoodsCalculationModel.Model model = getCurrentGLModel(tracker, refContext, rawContext );
if( model == null ) {
return null;
}
Map<String, AlignmentContext> stratifiedContexts = getFilteredAndStratifiedContexts(UAC, refContext, rawContext, model);
return calculateGenotypes(tracker, refContext, rawContext, stratifiedContexts, vc, model);
}
// ---------------------------------------------------------------------------------------------------------
//
// Private implementation helpers
//
// ---------------------------------------------------------------------------------------------------------
// private method called by both UnifiedGenotyper and UGCalcLikelihoods entry points into the engine
private VariantContext calculateLikelihoods(RefMetaDataTracker tracker, ReferenceContext refContext, Map<String, AlignmentContext> stratifiedContexts, AlignmentContextUtils.ReadOrientation type, Allele alternateAlleleToUse, boolean useBAQedPileup, final GenotypeLikelihoodsCalculationModel.Model model) {
// initialize the data for this thread if that hasn't been done yet
if ( glcm.get() == null ) {
glcm.set(getGenotypeLikelihoodsCalculationObject(logger, UAC));
}
return glcm.get().get(model).getLikelihoods(tracker, refContext, stratifiedContexts, type, getGenotypePriors(model), alternateAlleleToUse, useBAQedPileup && BAQEnabledOnCMDLine);
}
private VariantCallContext generateEmptyContext(RefMetaDataTracker tracker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, AlignmentContext rawContext) {
VariantContext vc;
if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
VariantContext vcInput = UnifiedGenotyperEngine.getVCFromAllelesRod(tracker, ref, rawContext.getLocation(), false, logger, UAC.alleles);
if ( vcInput == null )
return null;
vc = new VariantContextBuilder(vcInput).source("UG_call").noID().referenceBaseForIndel(ref.getBase()).make();
} else {
// deal with bad/non-standard reference bases
if ( !Allele.acceptableAlleleBases(new byte[]{ref.getBase()}) )
return null;
Set<Allele> alleles = new HashSet<Allele>();
alleles.add(Allele.create(ref.getBase(), true));
vc = new VariantContextBuilder("UG_call", ref.getLocus().getContig(), ref.getLocus().getStart(), ref.getLocus().getStart(), alleles).make();
}
if ( annotationEngine != null ) {
// Note: we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
vc = annotationEngine.annotateContext(tracker, ref, stratifiedContexts, vc);
}
return new VariantCallContext(vc, false);
}
public VariantCallContext calculateGenotypes(VariantContext vc, final GenotypeLikelihoodsCalculationModel.Model model) {
return calculateGenotypes(null, null, null, null, vc, model);
}
public VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc, final GenotypeLikelihoodsCalculationModel.Model model) {
boolean limitedContext = tracker == null || refContext == null || rawContext == null || stratifiedContexts == null;
// initialize the data for this thread if that hasn't been done yet
if ( afcm.get() == null ) {
log10AlleleFrequencyLikelihoods.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
log10AlleleFrequencyPosteriors.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
afcm.set(getAlleleFrequencyCalculationObject(N, logger, verboseWriter, UAC));
}
// don't try to genotype too many alternate alleles
if ( vc.getAlternateAlleles().size() > UAC.MAX_ALTERNATE_ALLELES ) {
logger.warn("the Unified Genotyper is currently set to genotype at most " + UAC.MAX_ALTERNATE_ALLELES + " alternate alleles in a given context, but the context at " + vc.getChr() + ":" + vc.getStart() + " has " + vc.getAlternateAlleles().size() + " alternate alleles; see the --max_alternate_alleles argument");
return null;
}
// estimate our confidence in a reference call and return
if ( vc.getNSamples() == 0 ) {
if ( limitedContext )
return null;
return (UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES ?
estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), false, 1.0) :
generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext));
}
// 'zero' out the AFs (so that we don't have to worry if not all samples have reads at this position)
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vc.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
// is the most likely frequency conformation AC=0 for all alternate alleles?
boolean bestGuessIsRef = true;
// which alternate allele has the highest MLE AC?
int indexOfHighestAlt = -1;
int alleleCountOfHighestAlt = -1;
// determine which alternate alleles have AF>0
boolean[] altAllelesToUse = new boolean[vc.getAlternateAlleles().size()];
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
int indexOfBestAC = MathUtils.maxElementIndex(log10AlleleFrequencyPosteriors.get()[i]);
// if the most likely AC is not 0, then this is a good alternate allele to use
if ( indexOfBestAC != 0 ) {
altAllelesToUse[i] = true;
bestGuessIsRef = false;
}
// if in GENOTYPE_GIVEN_ALLELES mode, we still want to allow the use of a poor allele
else if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
altAllelesToUse[i] = true;
}
// keep track of the "best" alternate allele to use
if ( indexOfBestAC > alleleCountOfHighestAlt) {
alleleCountOfHighestAlt = indexOfBestAC;
indexOfHighestAlt = i;
}
}
// calculate p(f>0)
// TODO -- right now we just calculate it for the alt allele with highest AF, but the likelihoods need to be combined correctly over all AFs
double[] normalizedPosteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get()[indexOfHighestAlt]);
double sum = 0.0;
for (int i = 1; i <= N; i++)
sum += normalizedPosteriors[i];
double PofF = Math.min(sum, 1.0); // deal with precision errors
double phredScaledConfidence;
if ( !bestGuessIsRef || UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(normalizedPosteriors[0]);
if ( Double.isInfinite(phredScaledConfidence) )
phredScaledConfidence = -10.0 * log10AlleleFrequencyPosteriors.get()[0][0];
} else {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(PofF);
if ( Double.isInfinite(phredScaledConfidence) ) {
sum = 0.0;
for (int i = 1; i <= N; i++) {
if ( log10AlleleFrequencyPosteriors.get()[0][i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED )
break;
sum += log10AlleleFrequencyPosteriors.get()[0][i];
}
phredScaledConfidence = (MathUtils.compareDoubles(sum, 0.0) == 0 ? 0 : -10.0 * sum);
}
}
// return a null call if we don't pass the confidence cutoff or the most likely allele frequency is zero
if ( UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES && !passesEmitThreshold(phredScaledConfidence, bestGuessIsRef) ) {
// technically, at this point our confidence in a reference call isn't accurately estimated
// because it didn't take into account samples with no data, so let's get a better estimate
return limitedContext ? null : estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), true, 1.0 - PofF);
}
// strip out any alleles that aren't going to be used in the VariantContext
List<Allele> myAlleles;
if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.DISCOVERY ) {
myAlleles = new ArrayList<Allele>(vc.getAlleles().size());
myAlleles.add(vc.getReference());
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
if ( altAllelesToUse[i] )
myAlleles.add(vc.getAlternateAllele(i));
}
} else {
// use all of the alleles if we are given them by the user
myAlleles = vc.getAlleles();
}
// start constructing the resulting VC
GenomeLoc loc = genomeLocParser.createGenomeLoc(vc);
VariantContextBuilder builder = new VariantContextBuilder("UG_call", loc.getContig(), loc.getStart(), loc.getStop(), myAlleles);
builder.log10PError(phredScaledConfidence/-10.0);
if ( ! passesCallThreshold(phredScaledConfidence) )
builder.filters(filter);
- if ( !limitedContext )
+ if ( limitedContext ) {
+ builder.referenceBaseForIndel(vc.getReferenceBaseForIndel());
+ } else {
builder.referenceBaseForIndel(refContext.getBase());
+ }
// create the genotypes
GenotypesContext genotypes = assignGenotypes(vc, altAllelesToUse);
// print out stats if we have a writer
if ( verboseWriter != null && !limitedContext )
printVerboseData(refContext.getLocus().toString(), vc, PofF, phredScaledConfidence, normalizedPosteriors, model);
// *** note that calculating strand bias involves overwriting data structures, so we do that last
HashMap<String, Object> attributes = new HashMap<String, Object>();
// if the site was downsampled, record that fact
if ( !limitedContext && rawContext.hasPileupBeenDownsampled() )
attributes.put(VCFConstants.DOWNSAMPLED_KEY, true);
if ( UAC.COMPUTE_SLOD && !limitedContext && !bestGuessIsRef ) {
//final boolean DEBUG_SLOD = false;
// the overall lod
VariantContext vcOverall = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcOverall.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double overallLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double overallLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("overallLog10PofF=" + overallLog10PofF);
// the forward lod
VariantContext vcForward = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.FORWARD, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcForward.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double[] normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double forwardLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double forwardLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("forwardLog10PofNull=" + forwardLog10PofNull + ", forwardLog10PofF=" + forwardLog10PofF);
// the reverse lod
VariantContext vcReverse = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.REVERSE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcReverse.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double reverseLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double reverseLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("reverseLog10PofNull=" + reverseLog10PofNull + ", reverseLog10PofF=" + reverseLog10PofF);
double forwardLod = forwardLog10PofF + reverseLog10PofNull - overallLog10PofF;
double reverseLod = reverseLog10PofF + forwardLog10PofNull - overallLog10PofF;
//if ( DEBUG_SLOD ) System.out.println("forward lod=" + forwardLod + ", reverse lod=" + reverseLod);
// strand score is max bias between forward and reverse strands
double strandScore = Math.max(forwardLod, reverseLod);
// rescale by a factor of 10
strandScore *= 10.0;
//logger.debug(String.format("SLOD=%f", strandScore));
attributes.put("SB", strandScore);
}
// finish constructing the resulting VC
builder.genotypes(genotypes);
builder.attributes(attributes);
VariantContext vcCall = builder.make();
if ( annotationEngine != null && !limitedContext ) {
// Note: we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
vcCall = annotationEngine.annotateContext(tracker, refContext, stratifiedContexts, vcCall);
}
return new VariantCallContext(vcCall, confidentlyCalled(phredScaledConfidence, PofF));
}
private Map<String, AlignmentContext> getFilteredAndStratifiedContexts(UnifiedArgumentCollection UAC, ReferenceContext refContext, AlignmentContext rawContext, final GenotypeLikelihoodsCalculationModel.Model model) {
Map<String, AlignmentContext> stratifiedContexts = null;
if ( !BaseUtils.isRegularBase( refContext.getBase() ) )
return null;
if ( model == GenotypeLikelihoodsCalculationModel.Model.INDEL ) {
if (UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) {
// regular pileup in this case
ReadBackedPileup pileup = rawContext.getBasePileup() .getMappingFilteredPileup(UAC.MIN_BASE_QUALTY_SCORE);
// don't call when there is no coverage
if ( pileup.getNumberOfElements() == 0 && UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES )
return null;
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
} else {
// todo - tmp will get rid of extended events so this wont be needed
if (!rawContext.hasExtendedEventPileup())
return null;
ReadBackedExtendedEventPileup rawPileup = rawContext.getExtendedEventPileup();
// filter the context based on min mapping quality
ReadBackedExtendedEventPileup pileup = rawPileup.getMappingFilteredPileup(UAC.MIN_BASE_QUALTY_SCORE);
// don't call when there is no coverage
if ( pileup.getNumberOfElements() == 0 && UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES )
return null;
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
}
} else if ( model == GenotypeLikelihoodsCalculationModel.Model.SNP ) {
// stratify the AlignmentContext and cut by sample
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(rawContext.getBasePileup());
if( !(UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_SITES && UAC.GenotypingMode != GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) ) {
int numDeletions = 0;
for( final PileupElement p : rawContext.getBasePileup() ) {
if( p.isDeletion() ) { numDeletions++; }
}
if( ((double) numDeletions) / ((double) rawContext.getBasePileup().getNumberOfElements()) > UAC.MAX_DELETION_FRACTION ) {
return null;
}
}
}
return stratifiedContexts;
}
protected static void clearAFarray(double[][] AFs) {
for ( int i = 0; i < AFs.length; i++ ) {
for ( int j = 0; j < AFs[i].length; j++ ) {
AFs[i][j] = AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED;
}
}
}
private final static double[] binomialProbabilityDepthCache = new double[10000];
static {
for ( int i = 1; i < binomialProbabilityDepthCache.length; i++ ) {
binomialProbabilityDepthCache[i] = MathUtils.binomialProbability(0, i, 0.5);
}
}
private final double getRefBinomialProb(final int depth) {
if ( depth < binomialProbabilityDepthCache.length )
return binomialProbabilityDepthCache[depth];
else
return MathUtils.binomialProbability(0, depth, 0.5);
}
private VariantCallContext estimateReferenceConfidence(VariantContext vc, Map<String, AlignmentContext> contexts, double theta, boolean ignoreCoveredSamples, double initialPofRef) {
if ( contexts == null )
return null;
double P_of_ref = initialPofRef;
// for each sample that we haven't examined yet
for ( String sample : samples ) {
boolean isCovered = contexts.containsKey(sample);
if ( ignoreCoveredSamples && isCovered )
continue;
int depth = 0;
if (isCovered) {
AlignmentContext context = contexts.get(sample);
if (context.hasBasePileup())
depth = context.getBasePileup().depthOfCoverage();
else if (context.hasExtendedEventPileup())
depth = context.getExtendedEventPileup().depthOfCoverage();
}
P_of_ref *= 1.0 - (theta / 2.0) * getRefBinomialProb(depth);
}
return new VariantCallContext(vc, QualityUtils.phredScaleErrorRate(1.0 - P_of_ref) >= UAC.STANDARD_CONFIDENCE_FOR_CALLING, false);
}
protected void printVerboseData(String pos, VariantContext vc, double PofF, double phredScaledConfidence, double[] normalizedPosteriors, final GenotypeLikelihoodsCalculationModel.Model model) {
Allele refAllele = null, altAllele = null;
for ( Allele allele : vc.getAlleles() ) {
if ( allele.isReference() )
refAllele = allele;
else
altAllele = allele;
}
for (int i = 0; i <= N; i++) {
StringBuilder AFline = new StringBuilder("AFINFO\t");
AFline.append(pos);
AFline.append("\t");
AFline.append(refAllele);
AFline.append("\t");
if ( altAllele != null )
AFline.append(altAllele);
else
AFline.append("N/A");
AFline.append("\t");
AFline.append(i + "/" + N + "\t");
AFline.append(String.format("%.2f\t", ((float)i)/N));
AFline.append(String.format("%.8f\t", getAlleleFrequencyPriors(model)[i]));
if ( log10AlleleFrequencyPosteriors.get()[0][i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED)
AFline.append("0.00000000\t");
else
AFline.append(String.format("%.8f\t", log10AlleleFrequencyPosteriors.get()[i]));
AFline.append(String.format("%.8f\t", normalizedPosteriors[i]));
verboseWriter.println(AFline.toString());
}
verboseWriter.println("P(f>0) = " + PofF);
verboseWriter.println("Qscore = " + phredScaledConfidence);
verboseWriter.println();
}
protected boolean passesEmitThreshold(double conf, boolean bestGuessIsRef) {
return (UAC.OutputMode == OUTPUT_MODE.EMIT_ALL_CONFIDENT_SITES || !bestGuessIsRef) && conf >= Math.min(UAC.STANDARD_CONFIDENCE_FOR_CALLING, UAC.STANDARD_CONFIDENCE_FOR_EMITTING);
}
protected boolean passesCallThreshold(double conf) {
return conf >= UAC.STANDARD_CONFIDENCE_FOR_CALLING;
}
protected boolean confidentlyCalled(double conf, double PofF) {
return conf >= UAC.STANDARD_CONFIDENCE_FOR_CALLING ||
(UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES && QualityUtils.phredScaleErrorRate(PofF) >= UAC.STANDARD_CONFIDENCE_FOR_CALLING);
}
// decide whether we are currently processing SNPs, indels, or neither
private GenotypeLikelihoodsCalculationModel.Model getCurrentGLModel(final RefMetaDataTracker tracker, final ReferenceContext refContext,
final AlignmentContext rawContext ) {
if (rawContext.hasExtendedEventPileup() ) {
// todo - remove this code
if ((UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL) &&
(UAC.GenotypingMode != GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) )
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
else {
// no extended event pileup
// if we're genotyping given alleles and we have a requested SNP at this position, do SNP
if (UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES) {
VariantContext vcInput = UnifiedGenotyperEngine.getVCFromAllelesRod(tracker, refContext, rawContext.getLocation(), false, logger, UAC.alleles);
if (vcInput == null)
return null;
// todo - no support to genotype MNP's yet
if (vcInput.isMNP())
return null;
if (vcInput.isSNP()) {
if (( UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.SNP))
return GenotypeLikelihoodsCalculationModel.Model.SNP;
else
// ignore SNP's if user chose INDEL mode
return null;
}
else if ((vcInput.isIndel() || vcInput.isMixed()) && (UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL))
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
else {
// todo - this assumes SNP's take priority when BOTH is selected, should do a smarter way once extended events are removed
if( UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.BOTH || UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.SNP)
return GenotypeLikelihoodsCalculationModel.Model.SNP;
else if (UAC.GLmodel == GenotypeLikelihoodsCalculationModel.Model.INDEL)
return GenotypeLikelihoodsCalculationModel.Model.INDEL;
}
}
return null;
}
protected static void computeAlleleFrequencyPriors(final int N, final double[][] priors, final double theta) {
// the dimension here is the number of alternate alleles; with e.g. 2 alternate alleles the prior will be theta^2 / i
for (int alleles = 1; alleles <= priors.length; alleles++) {
double sum = 0.0;
// for each i
for (int i = 1; i <= N; i++) {
double value = Math.pow(theta, alleles) / (double)i;
priors[alleles-1][i] = Math.log10(value);
sum += value;
}
// null frequency for AF=0 is (1 - sum(all other frequencies))
priors[alleles-1][0] = Math.log10(1.0 - sum);
}
}
protected double[][] getAlleleFrequencyPriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
switch( model ) {
case SNP:
return log10AlleleFrequencyPriorsSNPs;
case INDEL:
return log10AlleleFrequencyPriorsIndels;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
}
private static GenotypePriors createGenotypePriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
GenotypePriors priors;
switch ( model ) {
case SNP:
// use flat priors for GLs
priors = new DiploidSNPGenotypePriors();
break;
case INDEL:
// create flat priors for Indels, actual priors will depend on event length to be genotyped
priors = new DiploidIndelGenotypePriors();
break;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
return priors;
}
protected GenotypePriors getGenotypePriors( final GenotypeLikelihoodsCalculationModel.Model model ) {
switch( model ) {
case SNP:
return genotypePriorsSNPs;
case INDEL:
return genotypePriorsIndels;
default: throw new IllegalArgumentException("Unexpected GenotypeCalculationModel " + model);
}
}
private static Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel> getGenotypeLikelihoodsCalculationObject(Logger logger, UnifiedArgumentCollection UAC) {
Map<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel> glcm = new HashMap<GenotypeLikelihoodsCalculationModel.Model, GenotypeLikelihoodsCalculationModel>();
glcm.put(GenotypeLikelihoodsCalculationModel.Model.SNP, new SNPGenotypeLikelihoodsCalculationModel(UAC, logger));
glcm.put(GenotypeLikelihoodsCalculationModel.Model.INDEL, new IndelGenotypeLikelihoodsCalculationModel(UAC, logger));
return glcm;
}
private static AlleleFrequencyCalculationModel getAlleleFrequencyCalculationObject(int N, Logger logger, PrintStream verboseWriter, UnifiedArgumentCollection UAC) {
AlleleFrequencyCalculationModel afcm;
switch ( UAC.AFmodel ) {
case EXACT:
afcm = new ExactAFCalculationModel(UAC, N, logger, verboseWriter);
break;
default: throw new IllegalArgumentException("Unexpected AlleleFrequencyCalculationModel " + UAC.AFmodel);
}
return afcm;
}
public static VariantContext getVCFromAllelesRod(RefMetaDataTracker tracker, ReferenceContext ref, GenomeLoc loc, boolean requireSNP, Logger logger, final RodBinding<VariantContext> allelesBinding) {
if ( tracker == null || ref == null || logger == null )
throw new ReviewedStingException("Bad arguments: tracker=" + tracker + " ref=" + ref + " logger=" + logger);
VariantContext vc = null;
// search for usable record
for( final VariantContext vc_input : tracker.getValues(allelesBinding, loc) ) {
if ( vc_input != null && ! vc_input.isFiltered() && (! requireSNP || vc_input.isSNP() )) {
if ( vc == null ) {
vc = vc_input;
} else {
logger.warn("Multiple valid VCF records detected in the alleles input file at site " + ref.getLocus() + ", only considering the first record");
}
}
}
return vc;
}
/**
* @param vc variant context with genotype likelihoods
* @param allelesToUse bit vector describing which alternate alleles from the vc are okay to use
*
* @return genotypes
*/
public GenotypesContext assignGenotypes(VariantContext vc,
boolean[] allelesToUse) {
final GenotypesContext GLs = vc.getGenotypes();
final List<String> sampleIndices = GLs.getSampleNamesOrderedByName();
final GenotypesContext calls = GenotypesContext.create();
for ( int k = GLs.size() - 1; k >= 0; k-- ) {
final String sample = sampleIndices.get(k);
final Genotype g = GLs.get(sample);
if ( !g.hasLikelihoods() )
continue;
final double[] likelihoods = g.getLikelihoods().getAsVector();
// if there is no mass on the likelihoods, then just no-call the sample
if ( MathUtils.sum(likelihoods) > SUM_GL_THRESH_NOCALL ) {
calls.add(new Genotype(g.getSampleName(), NO_CALL_ALLELES, Genotype.NO_LOG10_PERROR, null, null, false));
continue;
}
// genotype likelihoods are a linear vector that can be thought of as a row-wise upper triangular matrix of log10Likelihoods.
// so e.g. with 2 alt alleles the likelihoods are AA,AB,AC,BB,BC,CC and with 3 alt alleles they are AA,AB,AC,AD,BB,BC,BD,CC,CD,DD.
final int numAltAlleles = allelesToUse.length;
// start with the assumption that the ideal genotype is homozygous reference
Allele maxAllele1 = vc.getReference(), maxAllele2 = vc.getReference();
double maxLikelihoodSeen = likelihoods[0];
int indexOfMax = 0;
// keep track of some state
Allele firstAllele = vc.getReference();
int subtractor = numAltAlleles + 1;
int subtractionsMade = 0;
for ( int i = 1, PLindex = 1; i < likelihoods.length; i++, PLindex++ ) {
if ( PLindex == subtractor ) {
firstAllele = vc.getAlternateAllele(subtractionsMade);
PLindex -= subtractor;
subtractor--;
subtractionsMade++;
// we can skip this allele if it's not usable
if ( !allelesToUse[subtractionsMade-1] ) {
i += subtractor - 1;
PLindex += subtractor - 1;
continue;
}
}
// we don't care about the entry if we've already seen better
if ( likelihoods[i] <= maxLikelihoodSeen )
continue;
// if it's usable then update the alleles
int alleleIndex = subtractionsMade + PLindex - 1;
if ( allelesToUse[alleleIndex] ) {
maxAllele1 = firstAllele;
maxAllele2 = vc.getAlternateAllele(alleleIndex);
maxLikelihoodSeen = likelihoods[i];
indexOfMax = i;
}
}
ArrayList<Allele> myAlleles = new ArrayList<Allele>();
myAlleles.add(maxAllele1);
myAlleles.add(maxAllele2);
final double qual = GenotypeLikelihoods.getQualFromLikelihoods(indexOfMax, likelihoods);
calls.add(new Genotype(sample, myAlleles, qual, null, g.getAttributes(), false));
}
return calls;
}
}
| false | true | public VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc, final GenotypeLikelihoodsCalculationModel.Model model) {
boolean limitedContext = tracker == null || refContext == null || rawContext == null || stratifiedContexts == null;
// initialize the data for this thread if that hasn't been done yet
if ( afcm.get() == null ) {
log10AlleleFrequencyLikelihoods.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
log10AlleleFrequencyPosteriors.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
afcm.set(getAlleleFrequencyCalculationObject(N, logger, verboseWriter, UAC));
}
// don't try to genotype too many alternate alleles
if ( vc.getAlternateAlleles().size() > UAC.MAX_ALTERNATE_ALLELES ) {
logger.warn("the Unified Genotyper is currently set to genotype at most " + UAC.MAX_ALTERNATE_ALLELES + " alternate alleles in a given context, but the context at " + vc.getChr() + ":" + vc.getStart() + " has " + vc.getAlternateAlleles().size() + " alternate alleles; see the --max_alternate_alleles argument");
return null;
}
// estimate our confidence in a reference call and return
if ( vc.getNSamples() == 0 ) {
if ( limitedContext )
return null;
return (UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES ?
estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), false, 1.0) :
generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext));
}
// 'zero' out the AFs (so that we don't have to worry if not all samples have reads at this position)
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vc.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
// is the most likely frequency conformation AC=0 for all alternate alleles?
boolean bestGuessIsRef = true;
// which alternate allele has the highest MLE AC?
int indexOfHighestAlt = -1;
int alleleCountOfHighestAlt = -1;
// determine which alternate alleles have AF>0
boolean[] altAllelesToUse = new boolean[vc.getAlternateAlleles().size()];
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
int indexOfBestAC = MathUtils.maxElementIndex(log10AlleleFrequencyPosteriors.get()[i]);
// if the most likely AC is not 0, then this is a good alternate allele to use
if ( indexOfBestAC != 0 ) {
altAllelesToUse[i] = true;
bestGuessIsRef = false;
}
// if in GENOTYPE_GIVEN_ALLELES mode, we still want to allow the use of a poor allele
else if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
altAllelesToUse[i] = true;
}
// keep track of the "best" alternate allele to use
if ( indexOfBestAC > alleleCountOfHighestAlt) {
alleleCountOfHighestAlt = indexOfBestAC;
indexOfHighestAlt = i;
}
}
// calculate p(f>0)
// TODO -- right now we just calculate it for the alt allele with highest AF, but the likelihoods need to be combined correctly over all AFs
double[] normalizedPosteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get()[indexOfHighestAlt]);
double sum = 0.0;
for (int i = 1; i <= N; i++)
sum += normalizedPosteriors[i];
double PofF = Math.min(sum, 1.0); // deal with precision errors
double phredScaledConfidence;
if ( !bestGuessIsRef || UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(normalizedPosteriors[0]);
if ( Double.isInfinite(phredScaledConfidence) )
phredScaledConfidence = -10.0 * log10AlleleFrequencyPosteriors.get()[0][0];
} else {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(PofF);
if ( Double.isInfinite(phredScaledConfidence) ) {
sum = 0.0;
for (int i = 1; i <= N; i++) {
if ( log10AlleleFrequencyPosteriors.get()[0][i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED )
break;
sum += log10AlleleFrequencyPosteriors.get()[0][i];
}
phredScaledConfidence = (MathUtils.compareDoubles(sum, 0.0) == 0 ? 0 : -10.0 * sum);
}
}
// return a null call if we don't pass the confidence cutoff or the most likely allele frequency is zero
if ( UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES && !passesEmitThreshold(phredScaledConfidence, bestGuessIsRef) ) {
// technically, at this point our confidence in a reference call isn't accurately estimated
// because it didn't take into account samples with no data, so let's get a better estimate
return limitedContext ? null : estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), true, 1.0 - PofF);
}
// strip out any alleles that aren't going to be used in the VariantContext
List<Allele> myAlleles;
if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.DISCOVERY ) {
myAlleles = new ArrayList<Allele>(vc.getAlleles().size());
myAlleles.add(vc.getReference());
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
if ( altAllelesToUse[i] )
myAlleles.add(vc.getAlternateAllele(i));
}
} else {
// use all of the alleles if we are given them by the user
myAlleles = vc.getAlleles();
}
// start constructing the resulting VC
GenomeLoc loc = genomeLocParser.createGenomeLoc(vc);
VariantContextBuilder builder = new VariantContextBuilder("UG_call", loc.getContig(), loc.getStart(), loc.getStop(), myAlleles);
builder.log10PError(phredScaledConfidence/-10.0);
if ( ! passesCallThreshold(phredScaledConfidence) )
builder.filters(filter);
if ( !limitedContext )
builder.referenceBaseForIndel(refContext.getBase());
// create the genotypes
GenotypesContext genotypes = assignGenotypes(vc, altAllelesToUse);
// print out stats if we have a writer
if ( verboseWriter != null && !limitedContext )
printVerboseData(refContext.getLocus().toString(), vc, PofF, phredScaledConfidence, normalizedPosteriors, model);
// *** note that calculating strand bias involves overwriting data structures, so we do that last
HashMap<String, Object> attributes = new HashMap<String, Object>();
// if the site was downsampled, record that fact
if ( !limitedContext && rawContext.hasPileupBeenDownsampled() )
attributes.put(VCFConstants.DOWNSAMPLED_KEY, true);
if ( UAC.COMPUTE_SLOD && !limitedContext && !bestGuessIsRef ) {
//final boolean DEBUG_SLOD = false;
// the overall lod
VariantContext vcOverall = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcOverall.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double overallLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double overallLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("overallLog10PofF=" + overallLog10PofF);
// the forward lod
VariantContext vcForward = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.FORWARD, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcForward.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double[] normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double forwardLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double forwardLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("forwardLog10PofNull=" + forwardLog10PofNull + ", forwardLog10PofF=" + forwardLog10PofF);
// the reverse lod
VariantContext vcReverse = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.REVERSE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcReverse.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double reverseLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double reverseLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("reverseLog10PofNull=" + reverseLog10PofNull + ", reverseLog10PofF=" + reverseLog10PofF);
double forwardLod = forwardLog10PofF + reverseLog10PofNull - overallLog10PofF;
double reverseLod = reverseLog10PofF + forwardLog10PofNull - overallLog10PofF;
//if ( DEBUG_SLOD ) System.out.println("forward lod=" + forwardLod + ", reverse lod=" + reverseLod);
// strand score is max bias between forward and reverse strands
double strandScore = Math.max(forwardLod, reverseLod);
// rescale by a factor of 10
strandScore *= 10.0;
//logger.debug(String.format("SLOD=%f", strandScore));
attributes.put("SB", strandScore);
}
// finish constructing the resulting VC
builder.genotypes(genotypes);
builder.attributes(attributes);
VariantContext vcCall = builder.make();
if ( annotationEngine != null && !limitedContext ) {
// Note: we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
vcCall = annotationEngine.annotateContext(tracker, refContext, stratifiedContexts, vcCall);
}
return new VariantCallContext(vcCall, confidentlyCalled(phredScaledConfidence, PofF));
}
| public VariantCallContext calculateGenotypes(RefMetaDataTracker tracker, ReferenceContext refContext, AlignmentContext rawContext, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc, final GenotypeLikelihoodsCalculationModel.Model model) {
boolean limitedContext = tracker == null || refContext == null || rawContext == null || stratifiedContexts == null;
// initialize the data for this thread if that hasn't been done yet
if ( afcm.get() == null ) {
log10AlleleFrequencyLikelihoods.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
log10AlleleFrequencyPosteriors.set(new double[UAC.MAX_ALTERNATE_ALLELES][N+1]);
afcm.set(getAlleleFrequencyCalculationObject(N, logger, verboseWriter, UAC));
}
// don't try to genotype too many alternate alleles
if ( vc.getAlternateAlleles().size() > UAC.MAX_ALTERNATE_ALLELES ) {
logger.warn("the Unified Genotyper is currently set to genotype at most " + UAC.MAX_ALTERNATE_ALLELES + " alternate alleles in a given context, but the context at " + vc.getChr() + ":" + vc.getStart() + " has " + vc.getAlternateAlleles().size() + " alternate alleles; see the --max_alternate_alleles argument");
return null;
}
// estimate our confidence in a reference call and return
if ( vc.getNSamples() == 0 ) {
if ( limitedContext )
return null;
return (UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES ?
estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), false, 1.0) :
generateEmptyContext(tracker, refContext, stratifiedContexts, rawContext));
}
// 'zero' out the AFs (so that we don't have to worry if not all samples have reads at this position)
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vc.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
// is the most likely frequency conformation AC=0 for all alternate alleles?
boolean bestGuessIsRef = true;
// which alternate allele has the highest MLE AC?
int indexOfHighestAlt = -1;
int alleleCountOfHighestAlt = -1;
// determine which alternate alleles have AF>0
boolean[] altAllelesToUse = new boolean[vc.getAlternateAlleles().size()];
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
int indexOfBestAC = MathUtils.maxElementIndex(log10AlleleFrequencyPosteriors.get()[i]);
// if the most likely AC is not 0, then this is a good alternate allele to use
if ( indexOfBestAC != 0 ) {
altAllelesToUse[i] = true;
bestGuessIsRef = false;
}
// if in GENOTYPE_GIVEN_ALLELES mode, we still want to allow the use of a poor allele
else if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
altAllelesToUse[i] = true;
}
// keep track of the "best" alternate allele to use
if ( indexOfBestAC > alleleCountOfHighestAlt) {
alleleCountOfHighestAlt = indexOfBestAC;
indexOfHighestAlt = i;
}
}
// calculate p(f>0)
// TODO -- right now we just calculate it for the alt allele with highest AF, but the likelihoods need to be combined correctly over all AFs
double[] normalizedPosteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get()[indexOfHighestAlt]);
double sum = 0.0;
for (int i = 1; i <= N; i++)
sum += normalizedPosteriors[i];
double PofF = Math.min(sum, 1.0); // deal with precision errors
double phredScaledConfidence;
if ( !bestGuessIsRef || UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.GENOTYPE_GIVEN_ALLELES ) {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(normalizedPosteriors[0]);
if ( Double.isInfinite(phredScaledConfidence) )
phredScaledConfidence = -10.0 * log10AlleleFrequencyPosteriors.get()[0][0];
} else {
phredScaledConfidence = QualityUtils.phredScaleErrorRate(PofF);
if ( Double.isInfinite(phredScaledConfidence) ) {
sum = 0.0;
for (int i = 1; i <= N; i++) {
if ( log10AlleleFrequencyPosteriors.get()[0][i] == AlleleFrequencyCalculationModel.VALUE_NOT_CALCULATED )
break;
sum += log10AlleleFrequencyPosteriors.get()[0][i];
}
phredScaledConfidence = (MathUtils.compareDoubles(sum, 0.0) == 0 ? 0 : -10.0 * sum);
}
}
// return a null call if we don't pass the confidence cutoff or the most likely allele frequency is zero
if ( UAC.OutputMode != OUTPUT_MODE.EMIT_ALL_SITES && !passesEmitThreshold(phredScaledConfidence, bestGuessIsRef) ) {
// technically, at this point our confidence in a reference call isn't accurately estimated
// because it didn't take into account samples with no data, so let's get a better estimate
return limitedContext ? null : estimateReferenceConfidence(vc, stratifiedContexts, getGenotypePriors(model).getHeterozygosity(), true, 1.0 - PofF);
}
// strip out any alleles that aren't going to be used in the VariantContext
List<Allele> myAlleles;
if ( UAC.GenotypingMode == GenotypeLikelihoodsCalculationModel.GENOTYPING_MODE.DISCOVERY ) {
myAlleles = new ArrayList<Allele>(vc.getAlleles().size());
myAlleles.add(vc.getReference());
for ( int i = 0; i < vc.getAlternateAlleles().size(); i++ ) {
if ( altAllelesToUse[i] )
myAlleles.add(vc.getAlternateAllele(i));
}
} else {
// use all of the alleles if we are given them by the user
myAlleles = vc.getAlleles();
}
// start constructing the resulting VC
GenomeLoc loc = genomeLocParser.createGenomeLoc(vc);
VariantContextBuilder builder = new VariantContextBuilder("UG_call", loc.getContig(), loc.getStart(), loc.getStop(), myAlleles);
builder.log10PError(phredScaledConfidence/-10.0);
if ( ! passesCallThreshold(phredScaledConfidence) )
builder.filters(filter);
if ( limitedContext ) {
builder.referenceBaseForIndel(vc.getReferenceBaseForIndel());
} else {
builder.referenceBaseForIndel(refContext.getBase());
}
// create the genotypes
GenotypesContext genotypes = assignGenotypes(vc, altAllelesToUse);
// print out stats if we have a writer
if ( verboseWriter != null && !limitedContext )
printVerboseData(refContext.getLocus().toString(), vc, PofF, phredScaledConfidence, normalizedPosteriors, model);
// *** note that calculating strand bias involves overwriting data structures, so we do that last
HashMap<String, Object> attributes = new HashMap<String, Object>();
// if the site was downsampled, record that fact
if ( !limitedContext && rawContext.hasPileupBeenDownsampled() )
attributes.put(VCFConstants.DOWNSAMPLED_KEY, true);
if ( UAC.COMPUTE_SLOD && !limitedContext && !bestGuessIsRef ) {
//final boolean DEBUG_SLOD = false;
// the overall lod
VariantContext vcOverall = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.COMPLETE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcOverall.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double overallLog10PofNull = log10AlleleFrequencyPosteriors.get()[0];
double overallLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("overallLog10PofF=" + overallLog10PofF);
// the forward lod
VariantContext vcForward = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.FORWARD, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcForward.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//double[] normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double forwardLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double forwardLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("forwardLog10PofNull=" + forwardLog10PofNull + ", forwardLog10PofF=" + forwardLog10PofF);
// the reverse lod
VariantContext vcReverse = calculateLikelihoods(tracker, refContext, stratifiedContexts, AlignmentContextUtils.ReadOrientation.REVERSE, vc.getAlternateAllele(0), false, model);
clearAFarray(log10AlleleFrequencyLikelihoods.get());
clearAFarray(log10AlleleFrequencyPosteriors.get());
afcm.get().getLog10PNonRef(vcReverse.getGenotypes(), vc.getAlleles(), getAlleleFrequencyPriors(model), log10AlleleFrequencyLikelihoods.get(), log10AlleleFrequencyPosteriors.get());
//normalizedLog10Posteriors = MathUtils.normalizeFromLog10(log10AlleleFrequencyPosteriors.get(), true);
double reverseLog10PofNull = log10AlleleFrequencyPosteriors.get()[0][0];
double reverseLog10PofF = MathUtils.log10sumLog10(log10AlleleFrequencyPosteriors.get()[0], 1);
//if ( DEBUG_SLOD ) System.out.println("reverseLog10PofNull=" + reverseLog10PofNull + ", reverseLog10PofF=" + reverseLog10PofF);
double forwardLod = forwardLog10PofF + reverseLog10PofNull - overallLog10PofF;
double reverseLod = reverseLog10PofF + forwardLog10PofNull - overallLog10PofF;
//if ( DEBUG_SLOD ) System.out.println("forward lod=" + forwardLod + ", reverse lod=" + reverseLod);
// strand score is max bias between forward and reverse strands
double strandScore = Math.max(forwardLod, reverseLod);
// rescale by a factor of 10
strandScore *= 10.0;
//logger.debug(String.format("SLOD=%f", strandScore));
attributes.put("SB", strandScore);
}
// finish constructing the resulting VC
builder.genotypes(genotypes);
builder.attributes(attributes);
VariantContext vcCall = builder.make();
if ( annotationEngine != null && !limitedContext ) {
// Note: we want to use the *unfiltered* and *unBAQed* context for the annotations
ReadBackedPileup pileup = null;
if (rawContext.hasExtendedEventPileup())
pileup = rawContext.getExtendedEventPileup();
else if (rawContext.hasBasePileup())
pileup = rawContext.getBasePileup();
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(pileup);
vcCall = annotationEngine.annotateContext(tracker, refContext, stratifiedContexts, vcCall);
}
return new VariantCallContext(vcCall, confidentlyCalled(phredScaledConfidence, PofF));
}
|
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index af09fb7f..95d7054f 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -1,2550 +1,2533 @@
/*
* Copyright (C) 2007 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 android.media;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.app.PendingIntent;
import android.app.ProfileGroup;
import android.app.ProfileManager;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.VolumePanel;
import android.view.WindowManager;
import java.util.HashMap;
/**
* AudioManager provides access to volume and ringer mode control.
* <p>
* Use <code>Context.getSystemService(Context.AUDIO_SERVICE)</code> to get
* an instance of this class.
*/
public class AudioManager {
private final Context mContext;
private long mVolumeKeyUpTime;
private final boolean mUseMasterVolume;
private final boolean mUseVolumeKeySounds;
private static String TAG = "AudioManager";
private final ProfileManager mProfileManager;
private final WindowManager mWindowManager;
/**
* Broadcast intent, a hint for applications that audio is about to become
* 'noisy' due to a change in audio outputs. For example, this intent may
* be sent when a wired headset is unplugged, or when an A2DP audio
* sink is disconnected, and the audio system is about to automatically
* switch audio route to the speaker. Applications that are controlling
* audio streams may consider pausing, reducing volume or some other action
* on receipt of this intent so as not to surprise the user with audio
* from the speaker.
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
/**
* Sticky broadcast intent action indicating that the ringer mode has
* changed. Includes the new ringer mode.
*
* @see #EXTRA_RINGER_MODE
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
/**
* The new ringer mode.
*
* @see #RINGER_MODE_CHANGED_ACTION
* @see #RINGER_MODE_NORMAL
* @see #RINGER_MODE_SILENT
* @see #RINGER_MODE_VIBRATE
*/
public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
/**
* Broadcast intent action indicating that the vibrate setting has
* changed. Includes the vibrate type and its new setting.
*
* @see #EXTRA_VIBRATE_TYPE
* @see #EXTRA_VIBRATE_SETTING
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String VIBRATE_SETTING_CHANGED_ACTION =
"android.media.VIBRATE_SETTING_CHANGED";
/**
* @hide Broadcast intent when the volume for a particular stream type changes.
* Includes the stream, the new volume and previous volumes.
* Notes:
* - for internal platform use only, do not make public,
* - never used for "remote" volume changes
*
* @see #EXTRA_VOLUME_STREAM_TYPE
* @see #EXTRA_VOLUME_STREAM_VALUE
* @see #EXTRA_PREV_VOLUME_STREAM_VALUE
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
/**
* @hide Broadcast intent when the master volume changes.
* Includes the new volume
*
* @see #EXTRA_MASTER_VOLUME_VALUE
* @see #EXTRA_PREV_MASTER_VOLUME_VALUE
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String MASTER_VOLUME_CHANGED_ACTION =
"android.media.MASTER_VOLUME_CHANGED_ACTION";
/**
* @hide Broadcast intent when the master mute state changes.
* Includes the the new volume
*
* @see #EXTRA_MASTER_VOLUME_MUTED
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String MASTER_MUTE_CHANGED_ACTION =
"android.media.MASTER_MUTE_CHANGED_ACTION";
/**
* The new vibrate setting for a particular type.
*
* @see #VIBRATE_SETTING_CHANGED_ACTION
* @see #EXTRA_VIBRATE_TYPE
* @see #VIBRATE_SETTING_ON
* @see #VIBRATE_SETTING_OFF
* @see #VIBRATE_SETTING_ONLY_SILENT
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
*/
public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
/**
* The vibrate type whose setting has changed.
*
* @see #VIBRATE_SETTING_CHANGED_ACTION
* @see #VIBRATE_TYPE_NOTIFICATION
* @see #VIBRATE_TYPE_RINGER
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
*/
public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
/**
* @hide The stream type for the volume changed intent.
*/
public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
/**
* @hide The volume associated with the stream for the volume changed intent.
*/
public static final String EXTRA_VOLUME_STREAM_VALUE =
"android.media.EXTRA_VOLUME_STREAM_VALUE";
/**
* @hide The previous volume associated with the stream for the volume changed intent.
*/
public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
"android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
/**
* @hide The new master volume value for the master volume changed intent.
* Value is integer between 0 and 100 inclusive.
*/
public static final String EXTRA_MASTER_VOLUME_VALUE =
"android.media.EXTRA_MASTER_VOLUME_VALUE";
/**
* @hide The previous master volume value for the master volume changed intent.
* Value is integer between 0 and 100 inclusive.
*/
public static final String EXTRA_PREV_MASTER_VOLUME_VALUE =
"android.media.EXTRA_PREV_MASTER_VOLUME_VALUE";
/**
* @hide The new master volume mute state for the master mute changed intent.
* Value is boolean
*/
public static final String EXTRA_MASTER_VOLUME_MUTED =
"android.media.EXTRA_MASTER_VOLUME_MUTED";
/** The audio stream for phone calls */
public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
/** The audio stream for system sounds */
public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
/** The audio stream for the phone ring */
public static final int STREAM_RING = AudioSystem.STREAM_RING;
/** The audio stream for music playback */
public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
/** The audio stream for alarms */
public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
/** The audio stream for notifications */
public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
/** @hide The audio stream for phone calls when connected to bluetooth */
public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
/** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
/** The audio stream for DTMF Tones */
public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
/** @hide The audio stream for text to speech (TTS) */
public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
/** Number of audio streams */
/**
* @deprecated Use AudioSystem.getNumStreamTypes() instead
*/
@Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
/** @hide Default volume index values for audio streams */
public static final int[] DEFAULT_STREAM_VOLUME = new int[] {
4, // STREAM_VOICE_CALL
7, // STREAM_SYSTEM
5, // STREAM_RING
11, // STREAM_MUSIC
6, // STREAM_ALARM
5, // STREAM_NOTIFICATION
7, // STREAM_BLUETOOTH_SCO
7, // STREAM_SYSTEM_ENFORCED
11, // STREAM_DTMF
11 // STREAM_TTS
};
/**
* Increase the ringer volume.
*
* @see #adjustVolume(int, int)
* @see #adjustStreamVolume(int, int, int)
*/
public static final int ADJUST_RAISE = 1;
/**
* Decrease the ringer volume.
*
* @see #adjustVolume(int, int)
* @see #adjustStreamVolume(int, int, int)
*/
public static final int ADJUST_LOWER = -1;
/**
* Maintain the previous ringer volume. This may be useful when needing to
* show the volume toast without actually modifying the volume.
*
* @see #adjustVolume(int, int)
* @see #adjustStreamVolume(int, int, int)
*/
public static final int ADJUST_SAME = 0;
// Flags should be powers of 2!
/**
* Show a toast containing the current volume.
*
* @see #adjustStreamVolume(int, int, int)
* @see #adjustVolume(int, int)
* @see #setStreamVolume(int, int, int)
* @see #setRingerMode(int)
*/
public static final int FLAG_SHOW_UI = 1 << 0;
/**
* Whether to include ringer modes as possible options when changing volume.
* For example, if true and volume level is 0 and the volume is adjusted
* with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
* vibrate mode.
* <p>
* By default this is on for the ring stream. If this flag is included,
* this behavior will be present regardless of the stream type being
* affected by the ringer mode.
*
* @see #adjustVolume(int, int)
* @see #adjustStreamVolume(int, int, int)
*/
public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
/**
* Whether to play a sound when changing the volume.
* <p>
* If this is given to {@link #adjustVolume(int, int)} or
* {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
* in some cases (for example, the decided stream type is not
* {@link AudioManager#STREAM_RING}, or the volume is being adjusted
* downward).
*
* @see #adjustStreamVolume(int, int, int)
* @see #adjustVolume(int, int)
* @see #setStreamVolume(int, int, int)
*/
public static final int FLAG_PLAY_SOUND = 1 << 2;
/**
* Removes any sounds/vibrate that may be in the queue, or are playing (related to
* changing volume).
*/
public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
/**
* Whether to vibrate if going into the vibrate ringer mode.
*/
public static final int FLAG_VIBRATE = 1 << 4;
/**
* Indicates to VolumePanel that the volume slider should be disabled as user
* cannot change the stream volume
* @hide
*/
public static final int FLAG_FIXED_VOLUME = 1 << 5;
/**
* Ringer mode that will be silent and will not vibrate. (This overrides the
* vibrate setting.)
*
* @see #setRingerMode(int)
* @see #getRingerMode()
*/
public static final int RINGER_MODE_SILENT = 0;
/**
* Ringer mode that will be silent and will vibrate. (This will cause the
* phone ringer to always vibrate, but the notification vibrate to only
* vibrate if set.)
*
* @see #setRingerMode(int)
* @see #getRingerMode()
*/
public static final int RINGER_MODE_VIBRATE = 1;
/**
* Ringer mode that may be audible and may vibrate. It will be audible if
* the volume before changing out of this mode was audible. It will vibrate
* if the vibrate setting is on.
*
* @see #setRingerMode(int)
* @see #getRingerMode()
*/
public static final int RINGER_MODE_NORMAL = 2;
// maximum valid ringer mode value. Values must start from 0 and be contiguous.
private static final int RINGER_MODE_MAX = RINGER_MODE_NORMAL;
/**
* Vibrate type that corresponds to the ringer.
*
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @see #shouldVibrate(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public static final int VIBRATE_TYPE_RINGER = 0;
/**
* Vibrate type that corresponds to notifications.
*
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @see #shouldVibrate(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public static final int VIBRATE_TYPE_NOTIFICATION = 1;
/**
* Vibrate setting that suggests to never vibrate.
*
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public static final int VIBRATE_SETTING_OFF = 0;
/**
* Vibrate setting that suggests to vibrate when possible.
*
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public static final int VIBRATE_SETTING_ON = 1;
/**
* Vibrate setting that suggests to only vibrate when in the vibrate ringer
* mode.
*
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
/**
* Suggests using the default stream type. This may not be used in all
* places a stream type is needed.
*/
public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
private static IAudioService sService;
/**
* @hide
*/
public AudioManager(Context context) {
mContext = context;
mUseMasterVolume = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_useMasterVolume);
mUseVolumeKeySounds = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_useVolumeKeySounds);
mProfileManager = (ProfileManager) context.getSystemService(Context.PROFILE_SERVICE);
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
private static IAudioService getService()
{
if (sService != null) {
return sService;
}
IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
sService = IAudioService.Stub.asInterface(b);
return sService;
}
/**
* @hide
*/
public void preDispatchKeyEvent(KeyEvent event, int stream) {
/*
* If the user hits another key within the play sound delay, then
* cancel the sound
*/
int keyCode = event.getKeyCode();
if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
&& keyCode != KeyEvent.KEYCODE_VOLUME_MUTE
&& mVolumeKeyUpTime + VolumePanel.PLAY_SOUND_DELAY
> SystemClock.uptimeMillis()) {
/*
* The user has hit another key during the delay (e.g., 300ms)
* since the last volume key up, so cancel any sounds.
*/
if (mUseMasterVolume) {
adjustMasterVolume(ADJUST_SAME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
} else {
adjustSuggestedStreamVolume(ADJUST_SAME,
stream, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
}
}
/**
* @hide
*/
public void handleKeyDown(KeyEvent event, int stream) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
/*
* Adjust the volume in on key down since it is more
* responsive to the user.
*/
int direction;
boolean swapKeys = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.SWAP_VOLUME_KEYS, 0) == 1;
int rotation = mWindowManager.getDefaultDisplay().getRotation();
if (swapKeys
&& (rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_180)) {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_LOWER
: ADJUST_RAISE;
} else {
- int swapKeys = Settings.System.getInt(mContext.getContentResolver(),
- Settings.System.SWAP_VOLUME_KEYS_BY_ROTATE, 0);
- int rotation = mWindowManager.getDefaultDisplay().getRotation();
- if (swapKeys == 1 // phone or hybrid
- && (rotation == Surface.ROTATION_90
- || rotation == Surface.ROTATION_180)) {
- direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
- ? ADJUST_LOWER
- : ADJUST_RAISE;
- } else if (swapKeys == 2 // tablet
- && (rotation == Surface.ROTATION_180
- || rotation == Surface.ROTATION_270)) {
- direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
- ? ADJUST_LOWER
- : ADJUST_RAISE;
- } else {
- direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
- ? ADJUST_RAISE
- : ADJUST_LOWER;
- }
+ direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
+ ? ADJUST_RAISE
+ : ADJUST_LOWER;
}
int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
if (mUseMasterVolume) {
adjustMasterVolume(direction, flags);
} else {
adjustSuggestedStreamVolume(direction, stream, flags);
}
break;
case KeyEvent.KEYCODE_VOLUME_MUTE:
if (event.getRepeatCount() == 0) {
if (mUseMasterVolume) {
setMasterMute(!isMasterMute());
} else {
// TODO: Actually handle MUTE.
}
}
break;
}
}
/**
* @hide
*/
public void handleKeyUp(KeyEvent event, int stream) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
/*
* Play a sound. This is done on key up since we don't want the
* sound to play when a user holds down volume down to mute.
*/
if (mUseVolumeKeySounds) {
if (mUseMasterVolume) {
adjustMasterVolume(ADJUST_SAME, FLAG_PLAY_SOUND);
} else {
int flags = FLAG_PLAY_SOUND;
adjustSuggestedStreamVolume(
ADJUST_SAME,
stream,
flags);
}
}
mVolumeKeyUpTime = SystemClock.uptimeMillis();
break;
}
}
/**
* Adjusts the volume of a particular stream by one step in a direction.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
* {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or
* {@link #STREAM_ALARM}
* @param direction The direction to adjust the volume. One of
* {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
* {@link #ADJUST_SAME}.
* @param flags One or more flags.
* @see #adjustVolume(int, int)
* @see #setStreamVolume(int, int, int)
*/
public void adjustStreamVolume(int streamType, int direction, int flags) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
service.adjustMasterVolume(direction, flags);
} else {
service.adjustStreamVolume(streamType, direction, flags);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in adjustStreamVolume", e);
}
}
/**
* Adjusts the volume of the most relevant stream. For example, if a call is
* active, it will have the highest priority regardless of if the in-call
* screen is showing. Another example, if music is playing in the background
* and a call is not active, the music stream will be adjusted.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param direction The direction to adjust the volume. One of
* {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
* {@link #ADJUST_SAME}.
* @param flags One or more flags.
* @see #adjustSuggestedStreamVolume(int, int, int)
* @see #adjustStreamVolume(int, int, int)
* @see #setStreamVolume(int, int, int)
*/
public void adjustVolume(int direction, int flags) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
service.adjustMasterVolume(direction, flags);
} else {
service.adjustVolume(direction, flags);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in adjustVolume", e);
}
}
/**
* Adjusts the volume of the most relevant stream, or the given fallback
* stream.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param direction The direction to adjust the volume. One of
* {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
* {@link #ADJUST_SAME}.
* @param suggestedStreamType The stream type that will be used if there
* isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is valid here.
* @param flags One or more flags.
* @see #adjustVolume(int, int)
* @see #adjustStreamVolume(int, int, int)
* @see #setStreamVolume(int, int, int)
*/
public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
service.adjustMasterVolume(direction, flags);
} else {
service.adjustSuggestedStreamVolume(direction, suggestedStreamType, flags);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in adjustSuggestedStreamVolume", e);
}
}
/**
* Adjusts the master volume for the device's audio amplifier.
* <p>
*
* @param steps The number of volume steps to adjust. A positive
* value will raise the volume.
* @param flags One or more flags.
* @hide
*/
public void adjustMasterVolume(int steps, int flags) {
IAudioService service = getService();
try {
service.adjustMasterVolume(steps, flags);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in adjustMasterVolume", e);
}
}
/**
* Returns the current ringtone mode.
*
* @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
* {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
* @see #setRingerMode(int)
*/
public int getRingerMode() {
IAudioService service = getService();
try {
return service.getRingerMode();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getRingerMode", e);
return RINGER_MODE_NORMAL;
}
}
/**
* Checks valid ringer mode values.
*
* @return true if the ringer mode indicated is valid, false otherwise.
*
* @see #setRingerMode(int)
* @hide
*/
public static boolean isValidRingerMode(int ringerMode) {
if (ringerMode < 0 || ringerMode > RINGER_MODE_MAX) {
return false;
}
return true;
}
/**
* Returns the maximum volume index for a particular stream.
*
* @param streamType The stream type whose maximum volume index is returned.
* @return The maximum valid volume index for the stream.
* @see #getStreamVolume(int)
*/
public int getStreamMaxVolume(int streamType) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
return service.getMasterMaxVolume();
} else {
return service.getStreamMaxVolume(streamType);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getStreamMaxVolume", e);
return 0;
}
}
/**
* Returns the current volume index for a particular stream.
*
* @param streamType The stream type whose volume index is returned.
* @return The current volume index for the stream.
* @see #getStreamMaxVolume(int)
* @see #setStreamVolume(int, int, int)
*/
public int getStreamVolume(int streamType) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
return service.getMasterVolume();
} else {
return service.getStreamVolume(streamType);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getStreamVolume", e);
return 0;
}
}
/**
* Get last audible volume before stream was muted.
*
* @hide
*/
public int getLastAudibleStreamVolume(int streamType) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
return service.getLastAudibleMasterVolume();
} else {
return service.getLastAudibleStreamVolume(streamType);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getLastAudibleStreamVolume", e);
return 0;
}
}
/**
* Get the stream type whose volume is driving the UI sounds volume.
* UI sounds are screen lock/unlock, camera shutter, key clicks...
* @hide
*/
public int getMasterStreamType() {
IAudioService service = getService();
try {
return service.getMasterStreamType();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getMasterStreamType", e);
return STREAM_RING;
}
}
/**
* Sets the ringer mode.
* <p>
* Silent mode will mute the volume and will not vibrate. Vibrate mode will
* mute the volume and vibrate. Normal mode will be audible and may vibrate
* according to user settings.
*
* @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
* {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
* @see #getRingerMode()
*/
public void setRingerMode(int ringerMode) {
if (!isValidRingerMode(ringerMode)) {
return;
}
IAudioService service = getService();
try {
service.setRingerMode(ringerMode);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setRingerMode", e);
}
}
/**
* Sets the volume index for a particular stream.
*
* @param streamType The stream whose volume index should be set.
* @param index The volume index to set. See
* {@link #getStreamMaxVolume(int)} for the largest valid value.
* @param flags One or more flags.
* @see #getStreamMaxVolume(int)
* @see #getStreamVolume(int)
*/
public void setStreamVolume(int streamType, int index, int flags) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
service.setMasterVolume(index, flags);
} else {
service.setStreamVolume(streamType, index, flags);
}
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setStreamVolume", e);
}
}
/**
* Returns the maximum volume index for master volume.
*
* @hide
*/
public int getMasterMaxVolume() {
IAudioService service = getService();
try {
return service.getMasterMaxVolume();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getMasterMaxVolume", e);
return 0;
}
}
/**
* Returns the current volume index for master volume.
*
* @return The current volume index for master volume.
* @hide
*/
public int getMasterVolume() {
IAudioService service = getService();
try {
return service.getMasterVolume();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getMasterVolume", e);
return 0;
}
}
/**
* Get last audible volume before master volume was muted.
*
* @hide
*/
public int getLastAudibleMasterVolume() {
IAudioService service = getService();
try {
return service.getLastAudibleMasterVolume();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getLastAudibleMasterVolume", e);
return 0;
}
}
/**
* Sets the volume index for master volume.
*
* @param index The volume index to set. See
* {@link #getMasterMaxVolume(int)} for the largest valid value.
* @param flags One or more flags.
* @see #getMasterMaxVolume(int)
* @see #getMasterVolume(int)
* @hide
*/
public void setMasterVolume(int index, int flags) {
IAudioService service = getService();
try {
service.setMasterVolume(index, flags);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setMasterVolume", e);
}
}
/**
* Solo or unsolo a particular stream. All other streams are muted.
* <p>
* The solo command is protected against client process death: if a process
* with an active solo request on a stream dies, all streams that were muted
* because of this request will be unmuted automatically.
* <p>
* The solo requests for a given stream are cumulative: the AudioManager
* can receive several solo requests from one or more clients and the stream
* will be unsoloed only when the same number of unsolo requests are received.
* <p>
* For a better user experience, applications MUST unsolo a soloed stream
* in onPause() and solo is again in onResume() if appropriate.
*
* @param streamType The stream to be soloed/unsoloed.
* @param state The required solo state: true for solo ON, false for solo OFF
*/
public void setStreamSolo(int streamType, boolean state) {
IAudioService service = getService();
try {
service.setStreamSolo(streamType, state, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setStreamSolo", e);
}
}
/**
* Mute or unmute an audio stream.
* <p>
* The mute command is protected against client process death: if a process
* with an active mute request on a stream dies, this stream will be unmuted
* automatically.
* <p>
* The mute requests for a given stream are cumulative: the AudioManager
* can receive several mute requests from one or more clients and the stream
* will be unmuted only when the same number of unmute requests are received.
* <p>
* For a better user experience, applications MUST unmute a muted stream
* in onPause() and mute is again in onResume() if appropriate.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param streamType The stream to be muted/unmuted.
* @param state The required mute state: true for mute ON, false for mute OFF
*/
public void setStreamMute(int streamType, boolean state) {
IAudioService service = getService();
try {
service.setStreamMute(streamType, state, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setStreamMute", e);
}
}
/**
* get stream mute state.
*
* @hide
*/
public boolean isStreamMute(int streamType) {
IAudioService service = getService();
try {
return service.isStreamMute(streamType);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in isStreamMute", e);
return false;
}
}
/**
* set master mute state.
*
* @hide
*/
public void setMasterMute(boolean state) {
setMasterMute(state, FLAG_SHOW_UI);
}
/**
* set master mute state with optional flags.
*
* @hide
*/
public void setMasterMute(boolean state, int flags) {
IAudioService service = getService();
try {
service.setMasterMute(state, flags, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setMasterMute", e);
}
}
/**
* get master mute state.
*
* @hide
*/
public boolean isMasterMute() {
IAudioService service = getService();
try {
return service.isMasterMute();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in isMasterMute", e);
return false;
}
}
/**
* forces the stream controlled by hard volume keys
* specifying streamType == -1 releases control to the
* logic.
*
* @hide
*/
public void forceVolumeControlStream(int streamType) {
IAudioService service = getService();
try {
service.forceVolumeControlStream(streamType, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in forceVolumeControlStream", e);
}
}
/**
* Returns whether a particular type should vibrate according to user
* settings and the current ringer mode.
* <p>
* This shouldn't be needed by most clients that use notifications to
* vibrate. The notification manager will not vibrate if the policy doesn't
* allow it, so the client should always set a vibrate pattern and let the
* notification manager control whether or not to actually vibrate.
*
* @param vibrateType The type of vibrate. One of
* {@link #VIBRATE_TYPE_NOTIFICATION} or
* {@link #VIBRATE_TYPE_RINGER}.
* @return Whether the type should vibrate at the instant this method is
* called.
* @see #setVibrateSetting(int, int)
* @see #getVibrateSetting(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public boolean shouldVibrate(int vibrateType) {
String packageName = mContext.getPackageName();
// Don't apply profiles for "android" context, as these could
// come from the NotificationManager, and originate from a real package.
if (!packageName.equals("android")) {
ProfileGroup profileGroup = mProfileManager.getActiveProfileGroup(packageName);
if (profileGroup != null) {
Log.v(TAG, "shouldVibrate, group: " + profileGroup.getUuid()
+ " mode: " + profileGroup.getVibrateMode());
switch (profileGroup.getVibrateMode()) {
case OVERRIDE :
return true;
case SUPPRESS :
return false;
case DEFAULT :
// Drop through
}
}
} else {
Log.v(TAG, "Not applying override for 'android' package");
}
IAudioService service = getService();
try {
return service.shouldVibrate(vibrateType);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in shouldVibrate", e);
return false;
}
}
/**
* Returns whether the user's vibrate setting for a vibrate type.
* <p>
* This shouldn't be needed by most clients that want to vibrate, instead
* see {@link #shouldVibrate(int)}.
*
* @param vibrateType The type of vibrate. One of
* {@link #VIBRATE_TYPE_NOTIFICATION} or
* {@link #VIBRATE_TYPE_RINGER}.
* @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
* {@link #VIBRATE_SETTING_OFF}, or
* {@link #VIBRATE_SETTING_ONLY_SILENT}.
* @see #setVibrateSetting(int, int)
* @see #shouldVibrate(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public int getVibrateSetting(int vibrateType) {
IAudioService service = getService();
try {
return service.getVibrateSetting(vibrateType);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getVibrateSetting", e);
return VIBRATE_SETTING_OFF;
}
}
/**
* Sets the setting for when the vibrate type should vibrate.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param vibrateType The type of vibrate. One of
* {@link #VIBRATE_TYPE_NOTIFICATION} or
* {@link #VIBRATE_TYPE_RINGER}.
* @param vibrateSetting The vibrate setting, one of
* {@link #VIBRATE_SETTING_ON},
* {@link #VIBRATE_SETTING_OFF}, or
* {@link #VIBRATE_SETTING_ONLY_SILENT}.
* @see #getVibrateSetting(int)
* @see #shouldVibrate(int)
* @deprecated Applications should maintain their own vibrate policy based on
* current ringer mode that can be queried via {@link #getRingerMode()}.
*/
public void setVibrateSetting(int vibrateType, int vibrateSetting) {
IAudioService service = getService();
try {
service.setVibrateSetting(vibrateType, vibrateSetting);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setVibrateSetting", e);
}
}
/**
* Sets the speakerphone on or off.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param on set <var>true</var> to turn on speakerphone;
* <var>false</var> to turn it off
*/
public void setSpeakerphoneOn(boolean on){
IAudioService service = getService();
try {
service.setSpeakerphoneOn(on);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setSpeakerphoneOn", e);
}
}
/**
* Checks whether the speakerphone is on or off.
*
* @return true if speakerphone is on, false if it's off
*/
public boolean isSpeakerphoneOn() {
IAudioService service = getService();
try {
return service.isSpeakerphoneOn();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in isSpeakerphoneOn", e);
return false;
}
}
//====================================================================
// Bluetooth SCO control
/**
* Sticky broadcast intent action indicating that the bluetoooth SCO audio
* connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
* indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
* or {@link #SCO_AUDIO_STATE_CONNECTED}
*
* @see #startBluetoothSco()
* @deprecated Use {@link #ACTION_SCO_AUDIO_STATE_UPDATED} instead
*/
@Deprecated
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
"android.media.SCO_AUDIO_STATE_CHANGED";
/**
* Sticky broadcast intent action indicating that the bluetoooth SCO audio
* connection state has been updated.
* <p>This intent has two extras:
* <ul>
* <li> {@link #EXTRA_SCO_AUDIO_STATE} - The new SCO audio state. </li>
* <li> {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}- The previous SCO audio state. </li>
* </ul>
* <p> EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE can be any of:
* <ul>
* <li> {@link #SCO_AUDIO_STATE_DISCONNECTED}, </li>
* <li> {@link #SCO_AUDIO_STATE_CONNECTING} or </li>
* <li> {@link #SCO_AUDIO_STATE_CONNECTED}, </li>
* </ul>
* @see #startBluetoothSco()
*/
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_SCO_AUDIO_STATE_UPDATED =
"android.media.ACTION_SCO_AUDIO_STATE_UPDATED";
/**
* Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} or
* {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the new bluetooth SCO connection state.
*/
public static final String EXTRA_SCO_AUDIO_STATE =
"android.media.extra.SCO_AUDIO_STATE";
/**
* Extra for intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the previous
* bluetooth SCO connection state.
*/
public static final String EXTRA_SCO_AUDIO_PREVIOUS_STATE =
"android.media.extra.SCO_AUDIO_PREVIOUS_STATE";
/**
* Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
* indicating that the SCO audio channel is not established
*/
public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
/**
* Value for extra {@link #EXTRA_SCO_AUDIO_STATE} or {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}
* indicating that the SCO audio channel is established
*/
public static final int SCO_AUDIO_STATE_CONNECTED = 1;
/**
* Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
* indicating that the SCO audio channel is being established
*/
public static final int SCO_AUDIO_STATE_CONNECTING = 2;
/**
* Value for extra EXTRA_SCO_AUDIO_STATE indicating that
* there was an error trying to obtain the state
*/
public static final int SCO_AUDIO_STATE_ERROR = -1;
/**
* Indicates if current platform supports use of SCO for off call use cases.
* Application wanted to use bluetooth SCO audio when the phone is not in call
* must first call this method to make sure that the platform supports this
* feature.
* @return true if bluetooth SCO can be used for audio when not in call
* false otherwise
* @see #startBluetoothSco()
*/
public boolean isBluetoothScoAvailableOffCall() {
return mContext.getResources().getBoolean(
com.android.internal.R.bool.config_bluetooth_sco_off_call);
}
/**
* Start bluetooth SCO audio connection.
* <p>Requires Permission:
* {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
* <p>This method can be used by applications wanting to send and received audio
* to/from a bluetooth SCO headset while the phone is not in call.
* <p>As the SCO connection establishment can take several seconds,
* applications should not rely on the connection to be available when the method
* returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED}
* and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
* <p>As the ACTION_SCO_AUDIO_STATE_UPDATED intent is sticky, the application can check the SCO
* audio state before calling startBluetoothSco() by reading the intent returned by the receiver
* registration. If the state is already CONNECTED, no state change will be received via the
* intent after calling startBluetoothSco(). It is however useful to call startBluetoothSco()
* so that the connection stays active in case the current initiator stops the connection.
* <p>Unless the connection is already active as described above, the state will always
* transition from DISCONNECTED to CONNECTING and then either to CONNECTED if the connection
* succeeds or back to DISCONNECTED if the connection fails (e.g no headset is connected).
* <p>When finished with the SCO connection or if the establishment fails, the application must
* call {@link #stopBluetoothSco()} to clear the request and turn down the bluetooth connection.
* <p>Even if a SCO connection is established, the following restrictions apply on audio
* output streams so that they can be routed to SCO headset:
* <ul>
* <li> the stream type must be {@link #STREAM_VOICE_CALL} </li>
* <li> the format must be mono </li>
* <li> the sampling must be 16kHz or 8kHz </li>
* </ul>
* <p>The following restrictions apply on input streams:
* <ul>
* <li> the format must be mono </li>
* <li> the sampling must be 8kHz </li>
* </ul>
* <p>Note that the phone application always has the priority on the usage of the SCO
* connection for telephony. If this method is called while the phone is in call
* it will be ignored. Similarly, if a call is received or sent while an application
* is using the SCO connection, the connection will be lost for the application and NOT
* returned automatically when the call ends.
* @see #stopBluetoothSco()
* @see #ACTION_SCO_AUDIO_STATE_UPDATED
*/
public void startBluetoothSco(){
IAudioService service = getService();
try {
service.startBluetoothSco(mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in startBluetoothSco", e);
}
}
/**
* Stop bluetooth SCO audio connection.
* <p>Requires Permission:
* {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
* <p>This method must be called by applications having requested the use of
* bluetooth SCO audio with {@link #startBluetoothSco()}
* when finished with the SCO connection or if connection fails.
* @see #startBluetoothSco()
*/
public void stopBluetoothSco(){
IAudioService service = getService();
try {
service.stopBluetoothSco(mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in stopBluetoothSco", e);
}
}
/**
* Request use of Bluetooth SCO headset for communications.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param on set <var>true</var> to use bluetooth SCO for communications;
* <var>false</var> to not use bluetooth SCO for communications
*/
public void setBluetoothScoOn(boolean on){
IAudioService service = getService();
try {
service.setBluetoothScoOn(on);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setBluetoothScoOn", e);
}
}
/**
* Checks whether communications use Bluetooth SCO.
*
* @return true if SCO is used for communications;
* false if otherwise
*/
public boolean isBluetoothScoOn() {
IAudioService service = getService();
try {
return service.isBluetoothScoOn();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in isBluetoothScoOn", e);
return false;
}
}
/**
* @param on set <var>true</var> to route A2DP audio to/from Bluetooth
* headset; <var>false</var> disable A2DP audio
* @deprecated Do not use.
*/
@Deprecated public void setBluetoothA2dpOn(boolean on){
}
/**
* Checks whether A2DP audio routing to the Bluetooth headset is on or off.
*
* @return true if A2DP audio is being routed to/from Bluetooth headset;
* false if otherwise
*/
public boolean isBluetoothA2dpOn() {
if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP,"")
== AudioSystem.DEVICE_STATE_UNAVAILABLE) {
return false;
} else {
return true;
}
}
/**
* @hide
* Signals whether remote submix audio rerouting is enabled.
*/
public void setRemoteSubmixOn(boolean on, int address) {
IAudioService service = getService();
try {
service.setRemoteSubmixOn(on, address);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setRemoteSubmixOn", e);
}
}
/**
* Sets audio routing to the wired headset on or off.
*
* @param on set <var>true</var> to route audio to/from wired
* headset; <var>false</var> disable wired headset audio
* @deprecated Do not use.
*/
@Deprecated public void setWiredHeadsetOn(boolean on){
}
/**
* Checks whether a wired headset is connected or not.
* <p>This is not a valid indication that audio playback is
* actually over the wired headset as audio routing depends on other conditions.
*
* @return true if a wired headset is connected.
* false if otherwise
* @deprecated Use only to check is a headset is connected or not.
*/
public boolean isWiredHeadsetOn() {
if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"")
== AudioSystem.DEVICE_STATE_UNAVAILABLE &&
AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"")
== AudioSystem.DEVICE_STATE_UNAVAILABLE) {
return false;
} else {
return true;
}
}
/**
* Sets the microphone mute on or off.
* <p>
* This method should only be used by applications that replace the platform-wide
* management of audio settings or the main telephony application.
*
* @param on set <var>true</var> to mute the microphone;
* <var>false</var> to turn mute off
*/
public void setMicrophoneMute(boolean on){
AudioSystem.muteMicrophone(on);
}
/**
* Checks whether the microphone mute is on or off.
*
* @return true if microphone is muted, false if it's not
*/
public boolean isMicrophoneMute() {
return AudioSystem.isMicrophoneMuted();
}
/**
* Sets the audio mode.
* <p>
* The audio mode encompasses audio routing AND the behavior of
* the telephony layer. Therefore this method should only be used by applications that
* replace the platform-wide management of audio settings or the main telephony application.
* In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
* application when it places a phone call, as it will cause signals from the radio layer
* to feed the platform mixer.
*
* @param mode the requested audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
* {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
* Informs the HAL about the current audio state so that
* it can route the audio appropriately.
*/
public void setMode(int mode) {
IAudioService service = getService();
try {
service.setMode(mode, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setMode", e);
}
}
/**
* Returns the current audio mode.
*
* @return the current audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
* {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
* Returns the current current audio state from the HAL.
*/
public int getMode() {
IAudioService service = getService();
try {
return service.getMode();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in getMode", e);
return MODE_INVALID;
}
}
/* modes for setMode/getMode/setRoute/getRoute */
/**
* Audio harware modes.
*/
/**
* Invalid audio mode.
*/
public static final int MODE_INVALID = AudioSystem.MODE_INVALID;
/**
* Current audio mode. Used to apply audio routing to current mode.
*/
public static final int MODE_CURRENT = AudioSystem.MODE_CURRENT;
/**
* Normal audio mode: not ringing and no call established.
*/
public static final int MODE_NORMAL = AudioSystem.MODE_NORMAL;
/**
* Ringing audio mode. An incoming is being signaled.
*/
public static final int MODE_RINGTONE = AudioSystem.MODE_RINGTONE;
/**
* In call audio mode. A telephony call is established.
*/
public static final int MODE_IN_CALL = AudioSystem.MODE_IN_CALL;
/**
* In communication audio mode. An audio/video chat or VoIP call is established.
*/
public static final int MODE_IN_COMMUNICATION = AudioSystem.MODE_IN_COMMUNICATION;
/* Routing bits for setRouting/getRouting API */
/**
* Routing audio output to earpiece
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_EARPIECE = AudioSystem.ROUTE_EARPIECE;
/**
* Routing audio output to speaker
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_SPEAKER = AudioSystem.ROUTE_SPEAKER;
/**
* @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
/**
* Routing audio output to bluetooth SCO
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_BLUETOOTH_SCO = AudioSystem.ROUTE_BLUETOOTH_SCO;
/**
* Routing audio output to headset
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_HEADSET = AudioSystem.ROUTE_HEADSET;
/**
* Routing audio output to bluetooth A2DP
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_BLUETOOTH_A2DP = AudioSystem.ROUTE_BLUETOOTH_A2DP;
/**
* Used for mask parameter of {@link #setRouting(int,int,int)}.
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated public static final int ROUTE_ALL = AudioSystem.ROUTE_ALL;
/**
* Sets the audio routing for a specified mode
*
* @param mode audio mode to change route. E.g., MODE_RINGTONE.
* @param routes bit vector of routes requested, created from one or
* more of ROUTE_xxx types. Set bits indicate that route should be on
* @param mask bit vector of routes to change, created from one or more of
* ROUTE_xxx types. Unset bits indicate the route should be left unchanged
*
* @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
* setBluetoothScoOn() methods instead.
*/
@Deprecated
public void setRouting(int mode, int routes, int mask) {
}
/**
* Returns the current audio routing bit vector for a specified mode.
*
* @param mode audio mode to get route (e.g., MODE_RINGTONE)
* @return an audio route bit vector that can be compared with ROUTE_xxx
* bits
* @deprecated Do not query audio routing directly, use isSpeakerphoneOn(),
* isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
*/
@Deprecated
public int getRouting(int mode) {
return -1;
}
/**
* Checks whether any music is active.
*
* @return true if any music tracks are active.
*/
public boolean isMusicActive() {
return AudioSystem.isStreamActive(STREAM_MUSIC, 0);
}
/**
* @hide
* Checks whether speech recognition is active
* @return true if a recording with source {@link MediaRecorder.AudioSource#VOICE_RECOGNITION}
* is underway.
*/
public boolean isSpeechRecognitionActive() {
return AudioSystem.isSourceActive(MediaRecorder.AudioSource.VOICE_RECOGNITION);
}
/**
* @hide
* If the stream is active locally or remotely, adjust its volume according to the enforced
* priority rules.
* Note: only AudioManager.STREAM_MUSIC is supported at the moment
*/
public void adjustLocalOrRemoteStreamVolume(int streamType, int direction) {
if (streamType != STREAM_MUSIC) {
Log.w(TAG, "adjustLocalOrRemoteStreamVolume() doesn't support stream " + streamType);
}
IAudioService service = getService();
try {
service.adjustLocalOrRemoteStreamVolume(streamType, direction);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in adjustLocalOrRemoteStreamVolume", e);
}
}
/*
* Sets a generic audio configuration parameter. The use of these parameters
* are platform dependant, see libaudio
*
* ** Temporary interface - DO NOT USE
*
* TODO: Replace with a more generic key:value get/set mechanism
*
* param key name of parameter to set. Must not be null.
* param value value of parameter. Must not be null.
*/
/**
* @hide
* @deprecated Use {@link #setPrameters(String)} instead
*/
@Deprecated public void setParameter(String key, String value) {
setParameters(key+"="+value);
}
/**
* Sets a variable number of parameter values to audio hardware.
*
* @param keyValuePairs list of parameters key value pairs in the form:
* key1=value1;key2=value2;...
*
*/
public void setParameters(String keyValuePairs) {
AudioSystem.setParameters(keyValuePairs);
}
/**
* Sets a varaible number of parameter values to audio hardware.
*
* @param keys list of parameters
* @return list of parameters key value pairs in the form:
* key1=value1;key2=value2;...
*/
public String getParameters(String keys) {
return AudioSystem.getParameters(keys);
}
/* Sound effect identifiers */
/**
* Keyboard and direction pad click sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEY_CLICK = 0;
/**
* Focus has moved up
* @see #playSoundEffect(int)
*/
public static final int FX_FOCUS_NAVIGATION_UP = 1;
/**
* Focus has moved down
* @see #playSoundEffect(int)
*/
public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
/**
* Focus has moved left
* @see #playSoundEffect(int)
*/
public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
/**
* Focus has moved right
* @see #playSoundEffect(int)
*/
public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
/**
* IME standard keypress sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_STANDARD = 5;
/**
* IME spacebar keypress sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_SPACEBAR = 6;
/**
* IME delete keypress sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_DELETE = 7;
/**
* IME return_keypress sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_RETURN = 8;
/**
* @hide Number of sound effects
*/
public static final int NUM_SOUND_EFFECTS = 9;
/**
* Plays a sound effect (Key clicks, lid open/close...)
* @param effectType The type of sound effect. One of
* {@link #FX_KEY_CLICK},
* {@link #FX_FOCUS_NAVIGATION_UP},
* {@link #FX_FOCUS_NAVIGATION_DOWN},
* {@link #FX_FOCUS_NAVIGATION_LEFT},
* {@link #FX_FOCUS_NAVIGATION_RIGHT},
* {@link #FX_KEYPRESS_STANDARD},
* {@link #FX_KEYPRESS_SPACEBAR},
* {@link #FX_KEYPRESS_DELETE},
* {@link #FX_KEYPRESS_RETURN},
* NOTE: This version uses the UI settings to determine
* whether sounds are heard or not.
*/
public void playSoundEffect(int effectType) {
if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
return;
}
if (!querySoundEffectsEnabled()) {
return;
}
IAudioService service = getService();
try {
service.playSoundEffect(effectType);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in playSoundEffect"+e);
}
}
/**
* Plays a sound effect (Key clicks, lid open/close...)
* @param effectType The type of sound effect. One of
* {@link #FX_KEY_CLICK},
* {@link #FX_FOCUS_NAVIGATION_UP},
* {@link #FX_FOCUS_NAVIGATION_DOWN},
* {@link #FX_FOCUS_NAVIGATION_LEFT},
* {@link #FX_FOCUS_NAVIGATION_RIGHT},
* {@link #FX_KEYPRESS_STANDARD},
* {@link #FX_KEYPRESS_SPACEBAR},
* {@link #FX_KEYPRESS_DELETE},
* {@link #FX_KEYPRESS_RETURN},
* @param volume Sound effect volume.
* The volume value is a raw scalar so UI controls should be scaled logarithmically.
* If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
* NOTE: This version is for applications that have their own
* settings panel for enabling and controlling volume.
*/
public void playSoundEffect(int effectType, float volume) {
if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
return;
}
IAudioService service = getService();
try {
service.playSoundEffectVolume(effectType, volume);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in playSoundEffect"+e);
}
}
/**
* Settings has an in memory cache, so this is fast.
*/
private boolean querySoundEffectsEnabled() {
return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0) != 0;
}
/**
* Load Sound effects.
* This method must be called when sound effects are enabled.
*/
public void loadSoundEffects() {
IAudioService service = getService();
try {
service.loadSoundEffects();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in loadSoundEffects"+e);
}
}
/**
* Unload Sound effects.
* This method can be called to free some memory when
* sound effects are disabled.
*/
public void unloadSoundEffects() {
IAudioService service = getService();
try {
service.unloadSoundEffects();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in unloadSoundEffects"+e);
}
}
/**
* Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
* @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
*/
public static final int AUDIOFOCUS_GAIN = 1;
/**
* Used to indicate a temporary gain or request of audio focus, anticipated to last a short
* amount of time. Examples of temporary changes are the playback of driving directions, or an
* event notification.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
* @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
*/
public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
/**
* Used to indicate a temporary request of audio focus, anticipated to last a short
* amount of time, and where it is acceptable for other audio applications to keep playing
* after having lowered their output level (also referred to as "ducking").
* Examples of temporary changes are the playback of driving directions where playback of music
* in the background is acceptable.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
* @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
*/
public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
/**
* Used to indicate a loss of audio focus of unknown duration.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
*/
public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
/**
* Used to indicate a transient loss of audio focus.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
*/
public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
/**
* Used to indicate a transient loss of audio focus where the loser of the audio focus can
* lower its output volume if it wants to continue playing (also referred to as "ducking"), as
* the new focus owner doesn't require others to be silent.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
*/
public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
-1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
/**
* Interface definition for a callback to be invoked when the audio focus of the system is
* updated.
*/
public interface OnAudioFocusChangeListener {
/**
* Called on the listener to notify it the audio focus for this listener has been changed.
* The focusChange value indicates whether the focus was gained,
* whether the focus was lost, and whether that loss is transient, or whether the new focus
* holder will hold it for an unknown amount of time.
* When losing focus, listeners can use the focus change information to decide what
* behavior to adopt when losing focus. A music player could for instance elect to lower
* the volume of its music stream (duck) for transient focus losses, and pause otherwise.
* @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
* {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
* and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
*/
public void onAudioFocusChange(int focusChange);
}
/**
* Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
* to actual listener objects.
*/
private final HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
new HashMap<String, OnAudioFocusChangeListener>();
/**
* Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
* instance.
*/
private final Object mFocusListenerLock = new Object();
private OnAudioFocusChangeListener findFocusListener(String id) {
return mAudioFocusIdListenerMap.get(id);
}
/**
* Handler for audio focus events coming from the audio service.
*/
private final FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
new FocusEventHandlerDelegate();
/**
* Helper class to handle the forwarding of audio focus events to the appropriate listener
*/
private class FocusEventHandlerDelegate {
private final Handler mHandler;
FocusEventHandlerDelegate() {
Looper looper;
if ((looper = Looper.myLooper()) == null) {
looper = Looper.getMainLooper();
}
if (looper != null) {
// implement the event handler delegate to receive audio focus events
mHandler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
OnAudioFocusChangeListener listener = null;
synchronized(mFocusListenerLock) {
listener = findFocusListener((String)msg.obj);
}
if (listener != null) {
listener.onAudioFocusChange(msg.what);
}
}
};
} else {
mHandler = null;
}
}
Handler getHandler() {
return mHandler;
}
}
private final IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
public void dispatchAudioFocusChange(int focusChange, String id) {
Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
}
};
private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
if (l == null) {
return new String(this.toString());
} else {
return new String(this.toString() + l.toString());
}
}
/**
* @hide
* Registers a listener to be called when audio focus changes. Calling this method is optional
* before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
* will register the listener as well if it wasn't registered already.
* @param l the listener to be notified of audio focus changes.
*/
public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
synchronized(mFocusListenerLock) {
if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
return;
}
mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
}
}
/**
* @hide
* Causes the specified listener to not be called anymore when focus is gained or lost.
* @param l the listener to unregister.
*/
public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
// remove locally
synchronized(mFocusListenerLock) {
mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
}
}
/**
* A failed focus change request.
*/
public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
/**
* A successful focus change request.
*/
public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
/**
* Request audio focus.
* Send a request to obtain the audio focus
* @param l the listener to be notified of audio focus changes
* @param streamType the main audio stream type affected by the focus request
* @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
* is temporary, and focus will be abandonned shortly. Examples of transient requests are
* for the playback of driving directions, or notifications sounds.
* Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
* the previous focus owner to keep playing if it ducks its audio output.
* Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
* as the playback of a song or a video.
* @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
*/
public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
int status = AUDIOFOCUS_REQUEST_FAILED;
if ((durationHint < AUDIOFOCUS_GAIN) || (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK))
{
Log.e(TAG, "Invalid duration hint, audio focus request denied");
return status;
}
registerAudioFocusListener(l);
//TODO protect request by permission check?
IAudioService service = getService();
try {
status = service.requestAudioFocus(streamType, durationHint, mICallBack,
mAudioFocusDispatcher, getIdForAudioFocusListener(l),
mContext.getPackageName() /* package name */);
} catch (RemoteException e) {
Log.e(TAG, "Can't call requestAudioFocus() on AudioService due to "+e);
}
return status;
}
/**
* @hide
* Used internally by telephony package to request audio focus. Will cause the focus request
* to be associated with the "voice communication" identifier only used in AudioService
* to identify this use case.
* @param streamType use STREAM_RING for focus requests when ringing, VOICE_CALL for
* the establishment of the call
* @param durationHint the type of focus request. AUDIOFOCUS_GAIN_TRANSIENT is recommended so
* media applications resume after a call
*/
public void requestAudioFocusForCall(int streamType, int durationHint) {
IAudioService service = getService();
try {
service.requestAudioFocus(streamType, durationHint, mICallBack, null,
AudioService.IN_VOICE_COMM_FOCUS_ID,
"system" /* dump-friendly package name */);
} catch (RemoteException e) {
Log.e(TAG, "Can't call requestAudioFocusForCall() on AudioService due to "+e);
}
}
/**
* @hide
* Used internally by telephony package to abandon audio focus, typically after a call or
* when ringing ends and the call is rejected or not answered.
* Should match one or more calls to {@link #requestAudioFocusForCall(int, int)}.
*/
public void abandonAudioFocusForCall() {
IAudioService service = getService();
try {
service.abandonAudioFocus(null, AudioService.IN_VOICE_COMM_FOCUS_ID);
} catch (RemoteException e) {
Log.e(TAG, "Can't call abandonAudioFocusForCall() on AudioService due to "+e);
}
}
/**
* Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
* @param l the listener with which focus was requested.
* @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
*/
public int abandonAudioFocus(OnAudioFocusChangeListener l) {
int status = AUDIOFOCUS_REQUEST_FAILED;
unregisterAudioFocusListener(l);
IAudioService service = getService();
try {
status = service.abandonAudioFocus(mAudioFocusDispatcher,
getIdForAudioFocusListener(l));
} catch (RemoteException e) {
Log.e(TAG, "Can't call abandonAudioFocus() on AudioService due to "+e);
}
return status;
}
//====================================================================
// Remote Control
/**
* Register a component to be the sole receiver of MEDIA_BUTTON intents.
* @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
* that will receive the media button intent. This broadcast receiver must be declared
* in the application manifest. The package of the component must match that of
* the context you're registering from.
*/
public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
if (eventReceiver == null) {
return;
}
if (!eventReceiver.getPackageName().equals(mContext.getPackageName())) {
Log.e(TAG, "registerMediaButtonEventReceiver() error: " +
"receiver and context package names don't match");
return;
}
// construct a PendingIntent for the media button and register it
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
// the associated intent will be handled by the component being registered
mediaButtonIntent.setComponent(eventReceiver);
PendingIntent pi = PendingIntent.getBroadcast(mContext,
0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
registerMediaButtonIntent(pi, eventReceiver);
}
/**
* @hide
* no-op if (pi == null) or (eventReceiver == null)
*/
public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
if ((pi == null) || (eventReceiver == null)) {
Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");
return;
}
IAudioService service = getService();
try {
// pi != null
service.registerMediaButtonIntent(pi, eventReceiver);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in registerMediaButtonIntent"+e);
}
}
/**
* @hide
* Used internally by telephony package to register an intent receiver for ACTION_MEDIA_BUTTON.
* @param eventReceiver the component that will receive the media button key events,
* no-op if eventReceiver is null
*/
public void registerMediaButtonEventReceiverForCalls(ComponentName eventReceiver) {
if (eventReceiver == null) {
return;
}
IAudioService service = getService();
try {
// eventReceiver != null
service.registerMediaButtonEventReceiverForCalls(eventReceiver);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in registerMediaButtonEventReceiverForCalls", e);
}
}
/**
* @hide
*/
public void unregisterMediaButtonEventReceiverForCalls() {
IAudioService service = getService();
try {
service.unregisterMediaButtonEventReceiverForCalls();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in unregisterMediaButtonEventReceiverForCalls", e);
}
}
/**
* Unregister the receiver of MEDIA_BUTTON intents.
* @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
* that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
*/
public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
if (eventReceiver == null) {
return;
}
// construct a PendingIntent for the media button and unregister it
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
// the associated intent will be handled by the component being registered
mediaButtonIntent.setComponent(eventReceiver);
PendingIntent pi = PendingIntent.getBroadcast(mContext,
0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
unregisterMediaButtonIntent(pi, eventReceiver);
}
/**
* @hide
*/
public void unregisterMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
IAudioService service = getService();
try {
service.unregisterMediaButtonIntent(pi, eventReceiver);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in unregisterMediaButtonIntent"+e);
}
}
/**
* Registers the remote control client for providing information to display on the remote
* controls.
* @param rcClient The remote control client from which remote controls will receive
* information to display.
* @see RemoteControlClient
*/
public void registerRemoteControlClient(RemoteControlClient rcClient) {
if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
return;
}
IAudioService service = getService();
try {
int rcseId = service.registerRemoteControlClient(
rcClient.getRcMediaIntent(), /* mediaIntent */
rcClient.getIRemoteControlClient(),/* rcClient */
// used to match media button event receiver and audio focus
mContext.getPackageName()); /* packageName */
rcClient.setRcseId(rcseId);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in registerRemoteControlClient"+e);
}
}
/**
* Unregisters the remote control client that was providing information to display on the
* remote controls.
* @param rcClient The remote control client to unregister.
* @see #registerRemoteControlClient(RemoteControlClient)
*/
public void unregisterRemoteControlClient(RemoteControlClient rcClient) {
if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
return;
}
IAudioService service = getService();
try {
service.unregisterRemoteControlClient(rcClient.getRcMediaIntent(), /* mediaIntent */
rcClient.getIRemoteControlClient()); /* rcClient */
} catch (RemoteException e) {
Log.e(TAG, "Dead object in unregisterRemoteControlClient"+e);
}
}
/**
* @hide
* Registers a remote control display that will be sent information by remote control clients.
* @param rcd
*/
public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
if (rcd == null) {
return;
}
IAudioService service = getService();
try {
service.registerRemoteControlDisplay(rcd);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in registerRemoteControlDisplay " + e);
}
}
/**
* @hide
* Unregisters a remote control display that was sent information by remote control clients.
* @param rcd
*/
public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
if (rcd == null) {
return;
}
IAudioService service = getService();
try {
service.unregisterRemoteControlDisplay(rcd);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in unregisterRemoteControlDisplay " + e);
}
}
/**
* @hide
* Sets the artwork size a remote control display expects when receiving bitmaps.
* @param rcd
* @param w the maximum width of the expected bitmap. Negative values indicate it is
* useless to send artwork.
* @param h the maximum height of the expected bitmap. Negative values indicate it is
* useless to send artwork.
*/
public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
if (rcd == null) {
return;
}
IAudioService service = getService();
try {
service.remoteControlDisplayUsesBitmapSize(rcd, w, h);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in remoteControlDisplayUsesBitmapSize " + e);
}
}
// FIXME remove because we are not using intents anymore between AudioService and RcDisplay
/**
* @hide
* Broadcast intent action indicating that the displays on the remote controls
* should be updated because a new remote control client is now active. If there is no
* {@link #EXTRA_REMOTE_CONTROL_CLIENT}, the remote control display should be cleared
* because there is no valid client to supply it with information.
*
* @see #EXTRA_REMOTE_CONTROL_CLIENT
*/
public static final String REMOTE_CONTROL_CLIENT_CHANGED =
"android.media.REMOTE_CONTROL_CLIENT_CHANGED";
// FIXME remove because we are not using intents anymore between AudioService and RcDisplay
/**
* @hide
* The IRemoteControlClientDispatcher monotonically increasing generation counter.
*
* @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
*/
public static final String EXTRA_REMOTE_CONTROL_CLIENT_GENERATION =
"android.media.EXTRA_REMOTE_CONTROL_CLIENT_GENERATION";
// FIXME remove because we are not using intents anymore between AudioService and RcDisplay
/**
* @hide
* The name of the RemoteControlClient.
* This String is passed as the client name when calling methods from the
* IRemoteControlClientDispatcher interface.
*
* @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
*/
public static final String EXTRA_REMOTE_CONTROL_CLIENT_NAME =
"android.media.EXTRA_REMOTE_CONTROL_CLIENT_NAME";
// FIXME remove because we are not using intents anymore between AudioService and RcDisplay
/**
* @hide
* The media button event receiver associated with the RemoteControlClient.
* The {@link android.content.ComponentName} value of the event receiver can be retrieved with
* {@link android.content.ComponentName#unflattenFromString(String)}
*
* @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
*/
public static final String EXTRA_REMOTE_CONTROL_EVENT_RECEIVER =
"android.media.EXTRA_REMOTE_CONTROL_EVENT_RECEIVER";
// FIXME remove because we are not using intents anymore between AudioService and RcDisplay
/**
* @hide
* The flags describing what information has changed in the current remote control client.
*
* @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
*/
public static final String EXTRA_REMOTE_CONTROL_CLIENT_INFO_CHANGED =
"android.media.EXTRA_REMOTE_CONTROL_CLIENT_INFO_CHANGED";
/**
* @hide
* Reload audio settings. This method is called by Settings backup
* agent when audio settings are restored and causes the AudioService
* to read and apply restored settings.
*/
public void reloadAudioSettings() {
IAudioService service = getService();
try {
service.reloadAudioSettings();
} catch (RemoteException e) {
Log.e(TAG, "Dead object in reloadAudioSettings"+e);
}
}
/**
* {@hide}
*/
private final IBinder mICallBack = new Binder();
/**
* Checks whether the phone is in silent mode, with or without vibrate.
*
* @return true if phone is in silent mode, with or without vibrate.
*
* @see #getRingerMode()
*
* @hide pending API Council approval
*/
public boolean isSilentMode() {
int ringerMode = getRingerMode();
boolean silentMode =
(ringerMode == RINGER_MODE_SILENT) ||
(ringerMode == RINGER_MODE_VIBRATE);
return silentMode;
}
// This section re-defines new output device constants from AudioSystem, because the AudioSystem
// class is not used by other parts of the framework, which instead use definitions and methods
// from AudioManager. AudioSystem is an internal class used by AudioManager and AudioService.
/** {@hide} The audio output device code for the small speaker at the front of the device used
* when placing calls. Does not refer to an in-ear headphone without attached microphone,
* such as earbuds, earphones, or in-ear monitors (IEM). Those would be handled as a
* {@link #DEVICE_OUT_WIRED_HEADPHONE}.
*/
public static final int DEVICE_OUT_EARPIECE = AudioSystem.DEVICE_OUT_EARPIECE;
/** {@hide} The audio output device code for the built-in speaker */
public static final int DEVICE_OUT_SPEAKER = AudioSystem.DEVICE_OUT_SPEAKER;
/** {@hide} The audio output device code for a wired headset with attached microphone */
public static final int DEVICE_OUT_WIRED_HEADSET = AudioSystem.DEVICE_OUT_WIRED_HEADSET;
/** {@hide} The audio output device code for a wired headphone without attached microphone */
public static final int DEVICE_OUT_WIRED_HEADPHONE = AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
/** {@hide} The audio output device code for generic Bluetooth SCO, for voice */
public static final int DEVICE_OUT_BLUETOOTH_SCO = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
/** {@hide} The audio output device code for Bluetooth SCO Headset Profile (HSP) and
* Hands-Free Profile (HFP), for voice
*/
public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET =
AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
/** {@hide} The audio output device code for Bluetooth SCO car audio, for voice */
public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT =
AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
/** {@hide} The audio output device code for generic Bluetooth A2DP, for music */
public static final int DEVICE_OUT_BLUETOOTH_A2DP = AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP;
/** {@hide} The audio output device code for Bluetooth A2DP headphones, for music */
public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES =
AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
/** {@hide} The audio output device code for Bluetooth A2DP external speaker, for music */
public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER =
AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
/** {@hide} The audio output device code for S/PDIF or HDMI */
public static final int DEVICE_OUT_AUX_DIGITAL = AudioSystem.DEVICE_OUT_AUX_DIGITAL;
/** {@hide} The audio output device code for an analog wired headset attached via a
* docking station
*/
public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
/** {@hide} The audio output device code for a digital wired headset attached via a
* docking station
*/
public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET;
/** {@hide} The audio output device code for a USB audio accessory. The accessory is in USB host
* mode and the Android device in USB device mode
*/
public static final int DEVICE_OUT_USB_ACCESSORY = AudioSystem.DEVICE_OUT_USB_ACCESSORY;
/** {@hide} The audio output device code for a USB audio device. The device is in USB device
* mode and the Android device in USB host mode
*/
public static final int DEVICE_OUT_USB_DEVICE = AudioSystem.DEVICE_OUT_USB_DEVICE;
/** {@hide} This is not used as a returned value from {@link #getDevicesForStream}, but could be
* used in the future in a set method to select whatever default device is chosen by the
* platform-specific implementation.
*/
public static final int DEVICE_OUT_DEFAULT = AudioSystem.DEVICE_OUT_DEFAULT;
/**
* Return the enabled devices for the specified output stream type.
*
* @param streamType The stream type to query. One of
* {@link #STREAM_VOICE_CALL},
* {@link #STREAM_SYSTEM},
* {@link #STREAM_RING},
* {@link #STREAM_MUSIC},
* {@link #STREAM_ALARM},
* {@link #STREAM_NOTIFICATION},
* {@link #STREAM_DTMF}.
*
* @return The bit-mask "or" of audio output device codes for all enabled devices on this
* stream. Zero or more of
* {@link #DEVICE_OUT_EARPIECE},
* {@link #DEVICE_OUT_SPEAKER},
* {@link #DEVICE_OUT_WIRED_HEADSET},
* {@link #DEVICE_OUT_WIRED_HEADPHONE},
* {@link #DEVICE_OUT_BLUETOOTH_SCO},
* {@link #DEVICE_OUT_BLUETOOTH_SCO_HEADSET},
* {@link #DEVICE_OUT_BLUETOOTH_SCO_CARKIT},
* {@link #DEVICE_OUT_BLUETOOTH_A2DP},
* {@link #DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES},
* {@link #DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER},
* {@link #DEVICE_OUT_AUX_DIGITAL},
* {@link #DEVICE_OUT_ANLG_DOCK_HEADSET},
* {@link #DEVICE_OUT_DGTL_DOCK_HEADSET}.
* {@link #DEVICE_OUT_DEFAULT} is not used here.
*
* The implementation may support additional device codes beyond those listed, so
* the application should ignore any bits which it does not recognize.
* Note that the information may be imprecise when the implementation
* cannot distinguish whether a particular device is enabled.
*
* {@hide}
*/
public int getDevicesForStream(int streamType) {
switch (streamType) {
case STREAM_VOICE_CALL:
case STREAM_SYSTEM:
case STREAM_RING:
case STREAM_MUSIC:
case STREAM_ALARM:
case STREAM_NOTIFICATION:
case STREAM_DTMF:
return AudioSystem.getDevicesForStream(streamType);
default:
return 0;
}
}
/**
* Indicate wired accessory connection state change.
* @param device type of device connected/disconnected (AudioManager.DEVICE_OUT_xxx)
* @param state new connection state: 1 connected, 0 disconnected
* @param name device name
* {@hide}
*/
public void setWiredDeviceConnectionState(int device, int state, String name) {
IAudioService service = getService();
try {
service.setWiredDeviceConnectionState(device, state, name);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setWiredDeviceConnectionState "+e);
}
}
/**
* Indicate A2DP sink connection state change.
* @param device Bluetooth device connected/disconnected
* @param state new connection state (BluetoothProfile.STATE_xxx)
* @return a delay in ms that the caller should wait before broadcasting
* BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED intent.
* {@hide}
*/
public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state) {
IAudioService service = getService();
int delay = 0;
try {
delay = service.setBluetoothA2dpDeviceConnectionState(device, state);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setBluetoothA2dpDeviceConnectionState "+e);
} finally {
return delay;
}
}
/** {@hide} */
public IRingtonePlayer getRingtonePlayer() {
try {
return getService().getRingtonePlayer();
} catch (RemoteException e) {
return null;
}
}
/**
* Used as a key for {@link #getProperty} to request the native or optimal output sample rate
* for this device's primary output stream, in decimal Hz.
*/
public static final String PROPERTY_OUTPUT_SAMPLE_RATE =
"android.media.property.OUTPUT_SAMPLE_RATE";
/**
* Used as a key for {@link #getProperty} to request the native or optimal output buffer size
* for this device's primary output stream, in decimal PCM frames.
*/
public static final String PROPERTY_OUTPUT_FRAMES_PER_BUFFER =
"android.media.property.OUTPUT_FRAMES_PER_BUFFER";
/**
* Returns the value of the property with the specified key.
* @param key One of the strings corresponding to a property key: either
* {@link #PROPERTY_OUTPUT_SAMPLE_RATE} or
* {@link #PROPERTY_OUTPUT_FRAMES_PER_BUFFER}
* @return A string representing the associated value for that property key,
* or null if there is no value for that key.
*/
public String getProperty(String key) {
if (PROPERTY_OUTPUT_SAMPLE_RATE.equals(key)) {
int outputSampleRate = AudioSystem.getPrimaryOutputSamplingRate();
return outputSampleRate > 0 ? Integer.toString(outputSampleRate) : null;
} else if (PROPERTY_OUTPUT_FRAMES_PER_BUFFER.equals(key)) {
int outputFramesPerBuffer = AudioSystem.getPrimaryOutputFrameCount();
return outputFramesPerBuffer > 0 ? Integer.toString(outputFramesPerBuffer) : null;
} else {
// null or unknown key
return null;
}
}
}
| true | true | public void handleKeyDown(KeyEvent event, int stream) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
/*
* Adjust the volume in on key down since it is more
* responsive to the user.
*/
int direction;
boolean swapKeys = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.SWAP_VOLUME_KEYS, 0) == 1;
int rotation = mWindowManager.getDefaultDisplay().getRotation();
if (swapKeys
&& (rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_180)) {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_LOWER
: ADJUST_RAISE;
} else {
int swapKeys = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.SWAP_VOLUME_KEYS_BY_ROTATE, 0);
int rotation = mWindowManager.getDefaultDisplay().getRotation();
if (swapKeys == 1 // phone or hybrid
&& (rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_180)) {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_LOWER
: ADJUST_RAISE;
} else if (swapKeys == 2 // tablet
&& (rotation == Surface.ROTATION_180
|| rotation == Surface.ROTATION_270)) {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_LOWER
: ADJUST_RAISE;
} else {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_RAISE
: ADJUST_LOWER;
}
}
int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
if (mUseMasterVolume) {
adjustMasterVolume(direction, flags);
} else {
adjustSuggestedStreamVolume(direction, stream, flags);
}
break;
case KeyEvent.KEYCODE_VOLUME_MUTE:
if (event.getRepeatCount() == 0) {
if (mUseMasterVolume) {
setMasterMute(!isMasterMute());
} else {
// TODO: Actually handle MUTE.
}
}
break;
}
}
| public void handleKeyDown(KeyEvent event, int stream) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
/*
* Adjust the volume in on key down since it is more
* responsive to the user.
*/
int direction;
boolean swapKeys = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.SWAP_VOLUME_KEYS, 0) == 1;
int rotation = mWindowManager.getDefaultDisplay().getRotation();
if (swapKeys
&& (rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_180)) {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_LOWER
: ADJUST_RAISE;
} else {
direction = keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_RAISE
: ADJUST_LOWER;
}
int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
if (mUseMasterVolume) {
adjustMasterVolume(direction, flags);
} else {
adjustSuggestedStreamVolume(direction, stream, flags);
}
break;
case KeyEvent.KEYCODE_VOLUME_MUTE:
if (event.getRepeatCount() == 0) {
if (mUseMasterVolume) {
setMasterMute(!isMasterMute());
} else {
// TODO: Actually handle MUTE.
}
}
break;
}
}
|
diff --git a/src/plugin/bleachisback/LogiBlocks/BaseCommandListener.java b/src/plugin/bleachisback/LogiBlocks/BaseCommandListener.java
index 78a5550..5e71f44 100644
--- a/src/plugin/bleachisback/LogiBlocks/BaseCommandListener.java
+++ b/src/plugin/bleachisback/LogiBlocks/BaseCommandListener.java
@@ -1,695 +1,694 @@
package plugin.bleachisback.LogiBlocks;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import com.thevoxelbox.voxelsniper.SnipeData;
import com.thevoxelbox.voxelsniper.Sniper;
import com.thevoxelbox.voxelsniper.SniperBrushes;
import com.thevoxelbox.voxelsniper.brush.Brush;
import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush;
import com.thevoxelbox.voxelsniper.brush.perform.PerformerE;
import com.thevoxelbox.voxelsniper.brush.perform.vPerformer;
public class BaseCommandListener implements CommandExecutor
{
private LogiBlocksMain plugin;
private Server server;
private HashMap<String,Integer> minArgs=new HashMap<String,Integer>();
private HashMap<String,Integer> inventorySubs=new HashMap<String,Integer>();
public BaseCommandListener(LogiBlocksMain plugin)
{
this.plugin=plugin;
this.server=plugin.getServer();
minArgs.put("eject", 2);
minArgs.put("ej", 2);
minArgs.put("kill", 2);
minArgs.put("accelerate", 5);
minArgs.put("acc", 5);
minArgs.put("delay", 3);
minArgs.put("redstone", 2);
minArgs.put("rs", 2);
minArgs.put("explode", 5);
minArgs.put("equip", 4);
minArgs.put("repeat", 4);
minArgs.put("rp", 4);
minArgs.put("setflag", 3);
minArgs.put("sf", 3);
minArgs.put("inventory", 2);
minArgs.put("inv", 2);
minArgs.put("voxelsniper", 1);
minArgs.put("vs", 1);
inventorySubs.put("add",1);
inventorySubs.put("remove",1);
inventorySubs.put("removeall",1);
inventorySubs.put("clear",0);
inventorySubs.put("refill",0);
inventorySubs.put("set",2);
inventorySubs.put("copy",1);
inventorySubs.put("show",1);
}
public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args)
{
if(!(sender instanceof BlockCommandSender))
{
sender.sendMessage(ChatColor.DARK_RED+"That command is meant for command blocks!");
return true;
}
if(args.length<1)
{
return false;
}
BlockCommandSender block=(BlockCommandSender) sender;
//Debug code
/*String trace="Before filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!LogiBlocksMain.filter(args, block, cmd))
{
return false;
}
//Debug code
/*trace="After filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!minArgs.containsKey(args[0]))
{
return false;
}
if(args.length<minArgs.get(args[0]))
{
return false;
}
Entity entity=null;
switch(args[0])
{
case "eject":
case "ej":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.leaveVehicle();
break;
//end eject
case "kill":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
if(entity instanceof LivingEntity)
{
((LivingEntity)entity).setHealth(0);
}
else
{
entity.remove();
}
break;
//end kill
case "accelerate":
case "acc":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.setVelocity(new Vector(Double.parseDouble(args[2]),Double.parseDouble(args[3]),Double.parseDouble(args[4])));
break;
//end accelerate
case "delay":
String command="";
for(int i=2;i<args.length;i++)
{
command=command+args[i]+" ";
}
command.trim();
final String $command=command;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command);
}
}, Integer.parseInt(args[1]));
break;
//end delay
case "redstone":
case "rs":
ArrayList<Block> levers=new ArrayList<Block>();
for(BlockFace face:BlockFace.values())
{
Block $block=block.getBlock().getRelative(face);
if($block.getType()==Material.LEVER&&$block.getData()<8)
{
$block.setData((byte)($block.getData()+8),true);
levers.add($block);
}
}
if(levers.isEmpty())
{
return false;
}
final ArrayList<Block> $levers=levers;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
for(Block lever:$levers)
{
lever.setData((byte) (lever.getData()-8),true);
}
}
}, Integer.parseInt(args[1]));
break;
//end redstone
case "explode":
Location expLoc=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
if(args.length>=7)
{
block.getBlock().getWorld().createExplosion(expLoc.getX(),expLoc.getY(),expLoc.getZ(),Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]), Boolean.parseBoolean(args[4]));
}
else if(args.length==6)
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]));
}
else
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]));
}
break;
//end explode
case "equip":
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
case "chest":
case "chestplate":
case "shirt":
case "legs":
case "leggings":
case "pants":
case "feet":
case "boots":
case "shoes":
break;
default:
return false;
}
ItemStack item=LogiBlocksMain.parseItemStack(args[3]);
Entity equipEntity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(equipEntity==null||!(equipEntity instanceof LivingEntity))
{
return false;
}
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
((LivingEntity) equipEntity).getEquipment().setHelmet(item);
break;
case "chest":
case "chestplate":
case "shirt":
((LivingEntity) equipEntity).getEquipment().setChestplate(item);
break;
case "legs":
case "leggings":
case "pants":
((LivingEntity) equipEntity).getEquipment().setLeggings(item);
break;
case "feet":
case "boots":
case "shoes":
((LivingEntity) equipEntity).getEquipment().setBoots(item);
break;
}
break;
//end equip
case "repeat":
case "rp":
String command1="";
for(int i=3;i<args.length;i++)
{
command1=command1+args[i]+" ";
}
command1.trim();
final String $command1=command1;
final int id=server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command1);
}
}, 0, Integer.parseInt(args[1]));
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.getScheduler().cancelTask(id);
}
}, Integer.parseInt(args[2])*Integer.parseInt(args[1]));
break;
//end repeat
case "setflag":
case "sf":
if(args[2].toLowerCase().equals("true"))
{
plugin.flagConfig.set(args[1], true);
}
else if(args[2].toLowerCase().equals("false"))
{
plugin.flagConfig.set(args[1], false);
}
else if(plugin.flags.containsKey(args[2]))
{
try
{
plugin.flagConfig.set(args[1], plugin.flags.get(args[2]).onFlag(args[2], Arrays.copyOfRange(args, 3, args.length+1), (BlockCommandSender) sender));
}
catch (FlagFailureException e)
{
return true;
}
}
try
{
plugin.flagConfig.save(LogiBlocksMain.flagFile);
}
catch (IOException e)
{
e.printStackTrace();
}
break;
//end setflag
case "inventory":
case "inv":
ArrayList<Inventory> inventoryList= new ArrayList<Inventory>();
if((args[1].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[1]))
{
Location invLocation=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
for(int x=-1;x<=1;x++)
{
for(int y=-1;y<=1;y++)
{
for(int z=-1;z<=1;z++)
{
Block testBlock=invLocation.clone().add(x, y, z).getBlock();
if(testBlock.getState() instanceof InventoryHolder)
{
inventoryList.add(((InventoryHolder) testBlock.getState()).getInventory());
}
}
}
}
}
else
{
Player player=Bukkit.getPlayer(args[1]);
if(player==null)
{
return false;
}
inventoryList.add(player.getInventory());
}
int subIndex=inventorySubs.containsKey(args[1])?1:2;
if(!inventorySubs.containsKey(args[subIndex]))
{
return false;
}
if(inventorySubs.get(args[subIndex])+subIndex+1>args.length)
{
return false;
}
for(Inventory inventory:inventoryList)
{
switch(args[subIndex])
{
case "add":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack item1=LogiBlocksMain.parseItemStack(args[i]);
if(item1==null)
{
continue;
}
inventory.addItem(item1);
}
break;
case "remove":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
if(removeItem==null)
{
continue;
}
for(ItemStack targetItem:inventory.getContents())
{
if(targetItem==null)
{
continue;
}
if(targetItem.isSimilar(removeItem))
{
if(removeItem.getAmount()>targetItem.getAmount())
{
removeItem.setAmount(removeItem.getAmount()-targetItem.getAmount());
inventory.remove(removeItem);
}
else
{
targetItem.setAmount(targetItem.getAmount()-removeItem.getAmount());
break;
}
}
}
}
break;
case "removeall":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
for(int j=1;j<=64;j++)
{
removeItem.setAmount(j);
inventory.remove(removeItem);
}
}
break;
case "clear":
inventory.clear();
break;
case "refill":
for(ItemStack itemStack:inventory.getContents())
{
if(itemStack==null)
{
continue;
}
itemStack.setAmount((args.length>subIndex+1?Boolean.parseBoolean(args[subIndex+1])?64:itemStack.getMaxStackSize():itemStack.getMaxStackSize()));
}
break;
case "set":
int slot=Integer.parseInt(args[subIndex+1]);
inventory.setItem(slot>=inventory.getSize()?inventory.getSize()-1:slot, LogiBlocksMain.parseItemStack(args[subIndex+2]));
break;
case "copy":
Inventory targetInventory;
if(args[subIndex+1].startsWith("@l[")&&args[subIndex+1].endsWith("]"))
{
Block targetBlock=LogiBlocksMain.parseLocation(args[subIndex+1], block.getBlock().getLocation()).getBlock();
if(targetBlock.getState() instanceof InventoryHolder)
{
targetInventory=((InventoryHolder) targetBlock.getState()).getInventory();
}
else
{
return false;
}
}
else
{
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
targetInventory=player.getInventory();
}
for(int i=0;i<inventory.getSize()&&i<targetInventory.getSize();i++)
{
targetInventory.setItem(i, inventory.getItem(i));
}
break;
case "show":
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
if(args.length>subIndex+2)
{
if(Boolean.parseBoolean(args[subIndex+2]))
{
Inventory fakeInventory=Bukkit.createInventory(inventory.getHolder(), inventory.getType());
fakeInventory.setContents(inventory.getContents());
player.openInventory(fakeInventory);
return true;
}
}
else
{
player.openInventory(inventory);
}
break;
}
}
break;
//end inventory
case "voxelsniper":
case "vs":
//Sets where the brush should be used at, should by the first arg after sub-command
Location location=LogiBlocksMain.parseLocation(args[1], block.getBlock().getRelative(BlockFace.UP).getLocation());
//Default brush attributes
String brushName="snipe";
String performer="m";
int brushSize=3;
int voxelId=0;
int replaceId=0;
byte data=0;
byte replaceData=0;
int voxelHeight=1;
//goes through every following arg and parses the attributes
//Attributes are named similarly to their voxelsniper command, meaning voxelId is v and replaceId is vr
for(int i=2; i<args.length; i++)
{
if(!args[i].contains("="))
{
continue;
}
args[i]=args[i].replace("-", "");
String att=args[i].substring(args[i].indexOf('=')+1,args[i].length());
switch(args[i].substring(0, args[i].indexOf('=')))
{
case "b":
//Check if brush exists
if(SniperBrushes.hasBrush(att))
{
brushName=att;
}
//If not, try to set brush size instead
else
{
try
{
brushSize=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
}
break;
case "p":
//Check if performer exists
//Only works with short names
if(PerformerE.has(att))
{
performer=att;
}
break;
case "v":
try
{
voxelId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vr":
try
{
replaceId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vi":
try
{
data=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vir":
try
{
replaceData=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vh":
try
{
voxelHeight=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
}
}
//end for
//Intanciates a new SnipeData object from VoxelSniper
- //null because there is no Player
SnipeData snipeData=new SnipeData(new Sniper());
snipeData.setBrushSize(brushSize);
snipeData.setData(data);
snipeData.setReplaceData(replaceData);
snipeData.setReplaceId(replaceId);
snipeData.setVoxelHeight(voxelHeight);
snipeData.setVoxelId(voxelId);
- //snipeData.setVoxelMessage(new Message(snipeData));
try
{
//gets a VoxelSniper brush instance, and sets the variables to be able to run
Brush brush=(Brush) SniperBrushes.getBrushInstance(brushName);
Field field=Brush.class.getDeclaredField("blockPositionX");
field.setAccessible(true);
field.set(brush, location.getBlockX());
field=Brush.class.getDeclaredField("blockPositionY");
field.setAccessible(true);
field.set(brush, location.getBlockY());
field=Brush.class.getDeclaredField("blockPositionZ");
field.setAccessible(true);
field.set(brush, location.getBlockZ());
field=Brush.class.getDeclaredField("world");
field.setAccessible(true);
field.set(brush, location.getWorld());
field=Brush.class.getDeclaredField("targetBlock");
field.setAccessible(true);
field.set(brush, location.getBlock());
if(brush instanceof PerformBrush)
{
vPerformer vperformer=PerformerE.getPerformer(performer);
field=PerformBrush.class.getDeclaredField("current");
field.setAccessible(true);
field.set(brush, vperformer);
field=vPerformer.class.getDeclaredField("w");
field.setAccessible(true);
field.set(vperformer, location.getWorld());
for(Field testField:vperformer.getClass().getDeclaredFields())
{
switch(testField.getName())
{
case "i":
testField.setAccessible(true);
testField.set(vperformer, voxelId);
break;
case "d":
testField.setAccessible(true);
testField.set(vperformer, data);
break;
- case "ir":
+ case "r":
testField.setAccessible(true);
testField.set(vperformer, replaceId);
break;
case "dr":
testField.setAccessible(true);
testField.set(vperformer, replaceData);
break;
}
}
vperformer.setUndo();
}
+ //Runs the brush
Method method=Brush.class.getDeclaredMethod("arrow", SnipeData.class);
method.setAccessible(true);
method.invoke(brush, snipeData);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
break;
//end voxelsniper
}
return false;
}
}
| false | true | public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args)
{
if(!(sender instanceof BlockCommandSender))
{
sender.sendMessage(ChatColor.DARK_RED+"That command is meant for command blocks!");
return true;
}
if(args.length<1)
{
return false;
}
BlockCommandSender block=(BlockCommandSender) sender;
//Debug code
/*String trace="Before filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!LogiBlocksMain.filter(args, block, cmd))
{
return false;
}
//Debug code
/*trace="After filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!minArgs.containsKey(args[0]))
{
return false;
}
if(args.length<minArgs.get(args[0]))
{
return false;
}
Entity entity=null;
switch(args[0])
{
case "eject":
case "ej":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.leaveVehicle();
break;
//end eject
case "kill":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
if(entity instanceof LivingEntity)
{
((LivingEntity)entity).setHealth(0);
}
else
{
entity.remove();
}
break;
//end kill
case "accelerate":
case "acc":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.setVelocity(new Vector(Double.parseDouble(args[2]),Double.parseDouble(args[3]),Double.parseDouble(args[4])));
break;
//end accelerate
case "delay":
String command="";
for(int i=2;i<args.length;i++)
{
command=command+args[i]+" ";
}
command.trim();
final String $command=command;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command);
}
}, Integer.parseInt(args[1]));
break;
//end delay
case "redstone":
case "rs":
ArrayList<Block> levers=new ArrayList<Block>();
for(BlockFace face:BlockFace.values())
{
Block $block=block.getBlock().getRelative(face);
if($block.getType()==Material.LEVER&&$block.getData()<8)
{
$block.setData((byte)($block.getData()+8),true);
levers.add($block);
}
}
if(levers.isEmpty())
{
return false;
}
final ArrayList<Block> $levers=levers;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
for(Block lever:$levers)
{
lever.setData((byte) (lever.getData()-8),true);
}
}
}, Integer.parseInt(args[1]));
break;
//end redstone
case "explode":
Location expLoc=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
if(args.length>=7)
{
block.getBlock().getWorld().createExplosion(expLoc.getX(),expLoc.getY(),expLoc.getZ(),Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]), Boolean.parseBoolean(args[4]));
}
else if(args.length==6)
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]));
}
else
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]));
}
break;
//end explode
case "equip":
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
case "chest":
case "chestplate":
case "shirt":
case "legs":
case "leggings":
case "pants":
case "feet":
case "boots":
case "shoes":
break;
default:
return false;
}
ItemStack item=LogiBlocksMain.parseItemStack(args[3]);
Entity equipEntity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(equipEntity==null||!(equipEntity instanceof LivingEntity))
{
return false;
}
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
((LivingEntity) equipEntity).getEquipment().setHelmet(item);
break;
case "chest":
case "chestplate":
case "shirt":
((LivingEntity) equipEntity).getEquipment().setChestplate(item);
break;
case "legs":
case "leggings":
case "pants":
((LivingEntity) equipEntity).getEquipment().setLeggings(item);
break;
case "feet":
case "boots":
case "shoes":
((LivingEntity) equipEntity).getEquipment().setBoots(item);
break;
}
break;
//end equip
case "repeat":
case "rp":
String command1="";
for(int i=3;i<args.length;i++)
{
command1=command1+args[i]+" ";
}
command1.trim();
final String $command1=command1;
final int id=server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command1);
}
}, 0, Integer.parseInt(args[1]));
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.getScheduler().cancelTask(id);
}
}, Integer.parseInt(args[2])*Integer.parseInt(args[1]));
break;
//end repeat
case "setflag":
case "sf":
if(args[2].toLowerCase().equals("true"))
{
plugin.flagConfig.set(args[1], true);
}
else if(args[2].toLowerCase().equals("false"))
{
plugin.flagConfig.set(args[1], false);
}
else if(plugin.flags.containsKey(args[2]))
{
try
{
plugin.flagConfig.set(args[1], plugin.flags.get(args[2]).onFlag(args[2], Arrays.copyOfRange(args, 3, args.length+1), (BlockCommandSender) sender));
}
catch (FlagFailureException e)
{
return true;
}
}
try
{
plugin.flagConfig.save(LogiBlocksMain.flagFile);
}
catch (IOException e)
{
e.printStackTrace();
}
break;
//end setflag
case "inventory":
case "inv":
ArrayList<Inventory> inventoryList= new ArrayList<Inventory>();
if((args[1].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[1]))
{
Location invLocation=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
for(int x=-1;x<=1;x++)
{
for(int y=-1;y<=1;y++)
{
for(int z=-1;z<=1;z++)
{
Block testBlock=invLocation.clone().add(x, y, z).getBlock();
if(testBlock.getState() instanceof InventoryHolder)
{
inventoryList.add(((InventoryHolder) testBlock.getState()).getInventory());
}
}
}
}
}
else
{
Player player=Bukkit.getPlayer(args[1]);
if(player==null)
{
return false;
}
inventoryList.add(player.getInventory());
}
int subIndex=inventorySubs.containsKey(args[1])?1:2;
if(!inventorySubs.containsKey(args[subIndex]))
{
return false;
}
if(inventorySubs.get(args[subIndex])+subIndex+1>args.length)
{
return false;
}
for(Inventory inventory:inventoryList)
{
switch(args[subIndex])
{
case "add":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack item1=LogiBlocksMain.parseItemStack(args[i]);
if(item1==null)
{
continue;
}
inventory.addItem(item1);
}
break;
case "remove":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
if(removeItem==null)
{
continue;
}
for(ItemStack targetItem:inventory.getContents())
{
if(targetItem==null)
{
continue;
}
if(targetItem.isSimilar(removeItem))
{
if(removeItem.getAmount()>targetItem.getAmount())
{
removeItem.setAmount(removeItem.getAmount()-targetItem.getAmount());
inventory.remove(removeItem);
}
else
{
targetItem.setAmount(targetItem.getAmount()-removeItem.getAmount());
break;
}
}
}
}
break;
case "removeall":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
for(int j=1;j<=64;j++)
{
removeItem.setAmount(j);
inventory.remove(removeItem);
}
}
break;
case "clear":
inventory.clear();
break;
case "refill":
for(ItemStack itemStack:inventory.getContents())
{
if(itemStack==null)
{
continue;
}
itemStack.setAmount((args.length>subIndex+1?Boolean.parseBoolean(args[subIndex+1])?64:itemStack.getMaxStackSize():itemStack.getMaxStackSize()));
}
break;
case "set":
int slot=Integer.parseInt(args[subIndex+1]);
inventory.setItem(slot>=inventory.getSize()?inventory.getSize()-1:slot, LogiBlocksMain.parseItemStack(args[subIndex+2]));
break;
case "copy":
Inventory targetInventory;
if(args[subIndex+1].startsWith("@l[")&&args[subIndex+1].endsWith("]"))
{
Block targetBlock=LogiBlocksMain.parseLocation(args[subIndex+1], block.getBlock().getLocation()).getBlock();
if(targetBlock.getState() instanceof InventoryHolder)
{
targetInventory=((InventoryHolder) targetBlock.getState()).getInventory();
}
else
{
return false;
}
}
else
{
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
targetInventory=player.getInventory();
}
for(int i=0;i<inventory.getSize()&&i<targetInventory.getSize();i++)
{
targetInventory.setItem(i, inventory.getItem(i));
}
break;
case "show":
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
if(args.length>subIndex+2)
{
if(Boolean.parseBoolean(args[subIndex+2]))
{
Inventory fakeInventory=Bukkit.createInventory(inventory.getHolder(), inventory.getType());
fakeInventory.setContents(inventory.getContents());
player.openInventory(fakeInventory);
return true;
}
}
else
{
player.openInventory(inventory);
}
break;
}
}
break;
//end inventory
case "voxelsniper":
case "vs":
//Sets where the brush should be used at, should by the first arg after sub-command
Location location=LogiBlocksMain.parseLocation(args[1], block.getBlock().getRelative(BlockFace.UP).getLocation());
//Default brush attributes
String brushName="snipe";
String performer="m";
int brushSize=3;
int voxelId=0;
int replaceId=0;
byte data=0;
byte replaceData=0;
int voxelHeight=1;
//goes through every following arg and parses the attributes
//Attributes are named similarly to their voxelsniper command, meaning voxelId is v and replaceId is vr
for(int i=2; i<args.length; i++)
{
if(!args[i].contains("="))
{
continue;
}
args[i]=args[i].replace("-", "");
String att=args[i].substring(args[i].indexOf('=')+1,args[i].length());
switch(args[i].substring(0, args[i].indexOf('=')))
{
case "b":
//Check if brush exists
if(SniperBrushes.hasBrush(att))
{
brushName=att;
}
//If not, try to set brush size instead
else
{
try
{
brushSize=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
}
break;
case "p":
//Check if performer exists
//Only works with short names
if(PerformerE.has(att))
{
performer=att;
}
break;
case "v":
try
{
voxelId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vr":
try
{
replaceId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vi":
try
{
data=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vir":
try
{
replaceData=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vh":
try
{
voxelHeight=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
}
}
//end for
//Intanciates a new SnipeData object from VoxelSniper
//null because there is no Player
SnipeData snipeData=new SnipeData(new Sniper());
snipeData.setBrushSize(brushSize);
snipeData.setData(data);
snipeData.setReplaceData(replaceData);
snipeData.setReplaceId(replaceId);
snipeData.setVoxelHeight(voxelHeight);
snipeData.setVoxelId(voxelId);
//snipeData.setVoxelMessage(new Message(snipeData));
try
{
//gets a VoxelSniper brush instance, and sets the variables to be able to run
Brush brush=(Brush) SniperBrushes.getBrushInstance(brushName);
Field field=Brush.class.getDeclaredField("blockPositionX");
field.setAccessible(true);
field.set(brush, location.getBlockX());
field=Brush.class.getDeclaredField("blockPositionY");
field.setAccessible(true);
field.set(brush, location.getBlockY());
field=Brush.class.getDeclaredField("blockPositionZ");
field.setAccessible(true);
field.set(brush, location.getBlockZ());
field=Brush.class.getDeclaredField("world");
field.setAccessible(true);
field.set(brush, location.getWorld());
field=Brush.class.getDeclaredField("targetBlock");
field.setAccessible(true);
field.set(brush, location.getBlock());
if(brush instanceof PerformBrush)
{
vPerformer vperformer=PerformerE.getPerformer(performer);
field=PerformBrush.class.getDeclaredField("current");
field.setAccessible(true);
field.set(brush, vperformer);
field=vPerformer.class.getDeclaredField("w");
field.setAccessible(true);
field.set(vperformer, location.getWorld());
for(Field testField:vperformer.getClass().getDeclaredFields())
{
switch(testField.getName())
{
case "i":
testField.setAccessible(true);
testField.set(vperformer, voxelId);
break;
case "d":
testField.setAccessible(true);
testField.set(vperformer, data);
break;
case "ir":
testField.setAccessible(true);
testField.set(vperformer, replaceId);
break;
case "dr":
testField.setAccessible(true);
testField.set(vperformer, replaceData);
break;
}
}
vperformer.setUndo();
}
Method method=Brush.class.getDeclaredMethod("arrow", SnipeData.class);
method.setAccessible(true);
method.invoke(brush, snipeData);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
break;
//end voxelsniper
}
return false;
}
| public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args)
{
if(!(sender instanceof BlockCommandSender))
{
sender.sendMessage(ChatColor.DARK_RED+"That command is meant for command blocks!");
return true;
}
if(args.length<1)
{
return false;
}
BlockCommandSender block=(BlockCommandSender) sender;
//Debug code
/*String trace="Before filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!LogiBlocksMain.filter(args, block, cmd))
{
return false;
}
//Debug code
/*trace="After filter: ";
for(String arg:args)
{
trace=trace+arg+" ";
}
trace(trace);*/
if(!minArgs.containsKey(args[0]))
{
return false;
}
if(args.length<minArgs.get(args[0]))
{
return false;
}
Entity entity=null;
switch(args[0])
{
case "eject":
case "ej":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.leaveVehicle();
break;
//end eject
case "kill":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
if(entity instanceof LivingEntity)
{
((LivingEntity)entity).setHealth(0);
}
else
{
entity.remove();
}
break;
//end kill
case "accelerate":
case "acc":
entity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(entity==null)
{
return false;
}
entity.setVelocity(new Vector(Double.parseDouble(args[2]),Double.parseDouble(args[3]),Double.parseDouble(args[4])));
break;
//end accelerate
case "delay":
String command="";
for(int i=2;i<args.length;i++)
{
command=command+args[i]+" ";
}
command.trim();
final String $command=command;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command);
}
}, Integer.parseInt(args[1]));
break;
//end delay
case "redstone":
case "rs":
ArrayList<Block> levers=new ArrayList<Block>();
for(BlockFace face:BlockFace.values())
{
Block $block=block.getBlock().getRelative(face);
if($block.getType()==Material.LEVER&&$block.getData()<8)
{
$block.setData((byte)($block.getData()+8),true);
levers.add($block);
}
}
if(levers.isEmpty())
{
return false;
}
final ArrayList<Block> $levers=levers;
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
for(Block lever:$levers)
{
lever.setData((byte) (lever.getData()-8),true);
}
}
}, Integer.parseInt(args[1]));
break;
//end redstone
case "explode":
Location expLoc=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
if(args.length>=7)
{
block.getBlock().getWorld().createExplosion(expLoc.getX(),expLoc.getY(),expLoc.getZ(),Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]), Boolean.parseBoolean(args[4]));
}
else if(args.length==6)
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]),Boolean.parseBoolean(args[3]));
}
else
{
block.getBlock().getWorld().createExplosion(expLoc,Integer.parseInt(args[2]));
}
break;
//end explode
case "equip":
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
case "chest":
case "chestplate":
case "shirt":
case "legs":
case "leggings":
case "pants":
case "feet":
case "boots":
case "shoes":
break;
default:
return false;
}
ItemStack item=LogiBlocksMain.parseItemStack(args[3]);
Entity equipEntity=LogiBlocksMain.parseEntity(args[1],block.getBlock().getWorld());
if(equipEntity==null||!(equipEntity instanceof LivingEntity))
{
return false;
}
switch(args[2].toLowerCase())
{
case "head":
case "helmet":
((LivingEntity) equipEntity).getEquipment().setHelmet(item);
break;
case "chest":
case "chestplate":
case "shirt":
((LivingEntity) equipEntity).getEquipment().setChestplate(item);
break;
case "legs":
case "leggings":
case "pants":
((LivingEntity) equipEntity).getEquipment().setLeggings(item);
break;
case "feet":
case "boots":
case "shoes":
((LivingEntity) equipEntity).getEquipment().setBoots(item);
break;
}
break;
//end equip
case "repeat":
case "rp":
String command1="";
for(int i=3;i<args.length;i++)
{
command1=command1+args[i]+" ";
}
command1.trim();
final String $command1=command1;
final int id=server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable()
{
public void run()
{
server.dispatchCommand(sender, $command1);
}
}, 0, Integer.parseInt(args[1]));
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
server.getScheduler().cancelTask(id);
}
}, Integer.parseInt(args[2])*Integer.parseInt(args[1]));
break;
//end repeat
case "setflag":
case "sf":
if(args[2].toLowerCase().equals("true"))
{
plugin.flagConfig.set(args[1], true);
}
else if(args[2].toLowerCase().equals("false"))
{
plugin.flagConfig.set(args[1], false);
}
else if(plugin.flags.containsKey(args[2]))
{
try
{
plugin.flagConfig.set(args[1], plugin.flags.get(args[2]).onFlag(args[2], Arrays.copyOfRange(args, 3, args.length+1), (BlockCommandSender) sender));
}
catch (FlagFailureException e)
{
return true;
}
}
try
{
plugin.flagConfig.save(LogiBlocksMain.flagFile);
}
catch (IOException e)
{
e.printStackTrace();
}
break;
//end setflag
case "inventory":
case "inv":
ArrayList<Inventory> inventoryList= new ArrayList<Inventory>();
if((args[1].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[1]))
{
Location invLocation=LogiBlocksMain.parseLocation(args[1], block.getBlock().getLocation());
for(int x=-1;x<=1;x++)
{
for(int y=-1;y<=1;y++)
{
for(int z=-1;z<=1;z++)
{
Block testBlock=invLocation.clone().add(x, y, z).getBlock();
if(testBlock.getState() instanceof InventoryHolder)
{
inventoryList.add(((InventoryHolder) testBlock.getState()).getInventory());
}
}
}
}
}
else
{
Player player=Bukkit.getPlayer(args[1]);
if(player==null)
{
return false;
}
inventoryList.add(player.getInventory());
}
int subIndex=inventorySubs.containsKey(args[1])?1:2;
if(!inventorySubs.containsKey(args[subIndex]))
{
return false;
}
if(inventorySubs.get(args[subIndex])+subIndex+1>args.length)
{
return false;
}
for(Inventory inventory:inventoryList)
{
switch(args[subIndex])
{
case "add":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack item1=LogiBlocksMain.parseItemStack(args[i]);
if(item1==null)
{
continue;
}
inventory.addItem(item1);
}
break;
case "remove":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
if(removeItem==null)
{
continue;
}
for(ItemStack targetItem:inventory.getContents())
{
if(targetItem==null)
{
continue;
}
if(targetItem.isSimilar(removeItem))
{
if(removeItem.getAmount()>targetItem.getAmount())
{
removeItem.setAmount(removeItem.getAmount()-targetItem.getAmount());
inventory.remove(removeItem);
}
else
{
targetItem.setAmount(targetItem.getAmount()-removeItem.getAmount());
break;
}
}
}
}
break;
case "removeall":
for(int i=subIndex+1;i<args.length;i++)
{
ItemStack removeItem=LogiBlocksMain.parseItemStack(args[i]);
for(int j=1;j<=64;j++)
{
removeItem.setAmount(j);
inventory.remove(removeItem);
}
}
break;
case "clear":
inventory.clear();
break;
case "refill":
for(ItemStack itemStack:inventory.getContents())
{
if(itemStack==null)
{
continue;
}
itemStack.setAmount((args.length>subIndex+1?Boolean.parseBoolean(args[subIndex+1])?64:itemStack.getMaxStackSize():itemStack.getMaxStackSize()));
}
break;
case "set":
int slot=Integer.parseInt(args[subIndex+1]);
inventory.setItem(slot>=inventory.getSize()?inventory.getSize()-1:slot, LogiBlocksMain.parseItemStack(args[subIndex+2]));
break;
case "copy":
Inventory targetInventory;
if(args[subIndex+1].startsWith("@l[")&&args[subIndex+1].endsWith("]"))
{
Block targetBlock=LogiBlocksMain.parseLocation(args[subIndex+1], block.getBlock().getLocation()).getBlock();
if(targetBlock.getState() instanceof InventoryHolder)
{
targetInventory=((InventoryHolder) targetBlock.getState()).getInventory();
}
else
{
return false;
}
}
else
{
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
targetInventory=player.getInventory();
}
for(int i=0;i<inventory.getSize()&&i<targetInventory.getSize();i++)
{
targetInventory.setItem(i, inventory.getItem(i));
}
break;
case "show":
Player player=Bukkit.getPlayer(args[subIndex+1]);
if(player==null)
{
return false;
}
if(args.length>subIndex+2)
{
if(Boolean.parseBoolean(args[subIndex+2]))
{
Inventory fakeInventory=Bukkit.createInventory(inventory.getHolder(), inventory.getType());
fakeInventory.setContents(inventory.getContents());
player.openInventory(fakeInventory);
return true;
}
}
else
{
player.openInventory(inventory);
}
break;
}
}
break;
//end inventory
case "voxelsniper":
case "vs":
//Sets where the brush should be used at, should by the first arg after sub-command
Location location=LogiBlocksMain.parseLocation(args[1], block.getBlock().getRelative(BlockFace.UP).getLocation());
//Default brush attributes
String brushName="snipe";
String performer="m";
int brushSize=3;
int voxelId=0;
int replaceId=0;
byte data=0;
byte replaceData=0;
int voxelHeight=1;
//goes through every following arg and parses the attributes
//Attributes are named similarly to their voxelsniper command, meaning voxelId is v and replaceId is vr
for(int i=2; i<args.length; i++)
{
if(!args[i].contains("="))
{
continue;
}
args[i]=args[i].replace("-", "");
String att=args[i].substring(args[i].indexOf('=')+1,args[i].length());
switch(args[i].substring(0, args[i].indexOf('=')))
{
case "b":
//Check if brush exists
if(SniperBrushes.hasBrush(att))
{
brushName=att;
}
//If not, try to set brush size instead
else
{
try
{
brushSize=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
}
break;
case "p":
//Check if performer exists
//Only works with short names
if(PerformerE.has(att))
{
performer=att;
}
break;
case "v":
try
{
voxelId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vr":
try
{
replaceId=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
case "vi":
try
{
data=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vir":
try
{
replaceData=Byte.parseByte(att);
}
catch(NumberFormatException e)
{
}
break;
case "vh":
try
{
voxelHeight=Integer.parseInt(att);
}
catch(NumberFormatException e)
{
}
break;
}
}
//end for
//Intanciates a new SnipeData object from VoxelSniper
SnipeData snipeData=new SnipeData(new Sniper());
snipeData.setBrushSize(brushSize);
snipeData.setData(data);
snipeData.setReplaceData(replaceData);
snipeData.setReplaceId(replaceId);
snipeData.setVoxelHeight(voxelHeight);
snipeData.setVoxelId(voxelId);
try
{
//gets a VoxelSniper brush instance, and sets the variables to be able to run
Brush brush=(Brush) SniperBrushes.getBrushInstance(brushName);
Field field=Brush.class.getDeclaredField("blockPositionX");
field.setAccessible(true);
field.set(brush, location.getBlockX());
field=Brush.class.getDeclaredField("blockPositionY");
field.setAccessible(true);
field.set(brush, location.getBlockY());
field=Brush.class.getDeclaredField("blockPositionZ");
field.setAccessible(true);
field.set(brush, location.getBlockZ());
field=Brush.class.getDeclaredField("world");
field.setAccessible(true);
field.set(brush, location.getWorld());
field=Brush.class.getDeclaredField("targetBlock");
field.setAccessible(true);
field.set(brush, location.getBlock());
if(brush instanceof PerformBrush)
{
vPerformer vperformer=PerformerE.getPerformer(performer);
field=PerformBrush.class.getDeclaredField("current");
field.setAccessible(true);
field.set(brush, vperformer);
field=vPerformer.class.getDeclaredField("w");
field.setAccessible(true);
field.set(vperformer, location.getWorld());
for(Field testField:vperformer.getClass().getDeclaredFields())
{
switch(testField.getName())
{
case "i":
testField.setAccessible(true);
testField.set(vperformer, voxelId);
break;
case "d":
testField.setAccessible(true);
testField.set(vperformer, data);
break;
case "r":
testField.setAccessible(true);
testField.set(vperformer, replaceId);
break;
case "dr":
testField.setAccessible(true);
testField.set(vperformer, replaceData);
break;
}
}
vperformer.setUndo();
}
//Runs the brush
Method method=Brush.class.getDeclaredMethod("arrow", SnipeData.class);
method.setAccessible(true);
method.invoke(brush, snipeData);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
break;
//end voxelsniper
}
return false;
}
|
diff --git a/ArabicaExpress/src/interfaccia/TratteTab.java b/ArabicaExpress/src/interfaccia/TratteTab.java
index 6dc314e..fa0cdfe 100644
--- a/ArabicaExpress/src/interfaccia/TratteTab.java
+++ b/ArabicaExpress/src/interfaccia/TratteTab.java
@@ -1,303 +1,303 @@
package interfaccia;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.persistence.PersistenceException;
import modelloTreni.Stazione;
import modelloTreni.StazioneTratta;
import modelloTreni.TrainException;
import modelloTreni.TrainManager;
import modelloTreni.Tratta;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
public class TratteTab {
private TabItem tabTratte;
private Composite tabTratteGroup, tratteButtonGroup,
stazioniTrattaButtonGroup;
private Table tabellaTratte, tabellaStazioniTratta;
private Button aggiungiTratta, rimuoviTratta, aggiungiStazioneTratta,
rimuoviStazioneTratta;
MainShell mainWindow = MainShell.getMainShell();
TrainManager manager = TrainManager.getInstance();
public TratteTab(TabFolder parent) {
tabTratte = new TabItem(parent, SWT.NONE);
tabTratteGroup = new Composite(parent, SWT.NONE);
createTabellaTratte();
createTabellaStazioniTratta();
createTratteButtonGroup();
createStazioniTrattaButtonGroup();
createTabellaTratteListener();
createTabellaStazioniTrattaListener();
createAggiungiTrattaListener();
createRimuoviTrattaListener();
createAggiungiStazioneTrattaListener();
createRimuoviStazioneTrattaListener();
tabTratteGroup.setLayout(new GridLayout(2, true));
tabTratte.setControl(tabTratteGroup);
}
private void createRimuoviStazioneTrattaListener() {
rimuoviStazioneTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
TableItem selezionetratta = tabellaTratte.getSelection()[0];
TableItem[] selezionestazione = tabellaStazioniTratta
.getSelection();
- int idtratta = Integer.parseInt(selezionetratta.getText(1));
+ int idtratta = Integer.parseInt(selezionetratta.getText(0));
String nomestazione = selezionestazione[0].getText(0);
try {
manager.removeStazioneFromTratta(idtratta, nomestazione);
tabellaStazioniTratta.removeAll();
loadTabellaStazioniTratta(selezionetratta);
} catch (PersistenceException e) {
// AlertShell alert = XXX
// new AlertShell(
// "E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
MessageBox alert = new MessageBox(MainShell.getMainShell()
.getShell(), SWT.ICON_ERROR | SWT.OK);
alert.setMessage("E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
alert.open();
return;
}
}
});
}
private void createAggiungiStazioneTrattaListener() {
aggiungiStazioneTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
final TableItem trattaSelezionata = tabellaTratte
.getSelection()[0];
Tratta tratta = manager.getTratta(trattaSelezionata.getText(1));
DialogAggiungiStazioneTratta d = new DialogAggiungiStazioneTratta(
tratta);
d.showDialog();
d.getDialog().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
loadTabellaStazioniTratta(trattaSelezionata);
orderTabellaStazioniTratta();
}
});
}
});
}
private void createRimuoviTrattaListener() {
rimuoviTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
TableItem[] selezione = tabellaTratte.getSelection();
try {
manager.removeTratta(selezione[0].getText());
} catch (Exception e) {
// AlertShell alert = XXX
// new AlertShell(
// "La tratta e' utilizzata in almeno una corsa.");
MessageBox alert = new MessageBox(MainShell.getMainShell().getShell(),SWT.ICON_ERROR | SWT.OK);
alert.setMessage("La tratta e' utilizzata in almeno una corsa.");
alert.open();
}
tabellaTratte.removeAll();
tabellaStazioniTratta.removeAll();
loadTabellaTratte();
rimuoviTratta.setEnabled(false);
}
});
}
private void createAggiungiTrattaListener() {
aggiungiTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
DialogAggiungiTratta d = new DialogAggiungiTratta();
d.showDialog();
d.getDialog().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
loadTabellaTratte();
}
});
// loadTabellaTratte();
}
});
}
private void createTabellaStazioniTrattaListener() {
tabellaStazioniTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
TableItem[] selezione = tabellaStazioniTratta.getSelection();
if (selezione.length != 0) {
rimuoviStazioneTratta.setEnabled(true);
} else {
rimuoviStazioneTratta.setEnabled(false);
}
}
});
}
private void createTabellaTratteListener() {
tabellaTratte.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
rimuoviTratta.setEnabled(true);
aggiungiStazioneTratta.setEnabled(true);
tabellaStazioniTratta.removeAll();
TableItem selezione = tabellaTratte.getSelection()[0];
TableItem[] selezione2 = tabellaStazioniTratta.getSelection();
if (selezione2.length == 0) {
rimuoviStazioneTratta.setEnabled(false);
}
loadTabellaStazioniTratta(selezione);
orderTabellaStazioniTratta();
}
});
}
private void createStazioniTrattaButtonGroup() {
stazioniTrattaButtonGroup = new Composite(tabTratteGroup, SWT.NONE);
stazioniTrattaButtonGroup.setLayoutData(new GridData(SWT.FILL,
SWT.FILL, false, false));
stazioniTrattaButtonGroup.setLayout(new GridLayout(2, true));
aggiungiStazioneTratta = new Button(stazioniTrattaButtonGroup, SWT.PUSH);
aggiungiStazioneTratta.setText("+");
aggiungiStazioneTratta.setEnabled(false);
rimuoviStazioneTratta = new Button(stazioniTrattaButtonGroup, SWT.PUSH);
rimuoviStazioneTratta.setText("-");
rimuoviStazioneTratta.setEnabled(false);
}
private void createTratteButtonGroup() {
tratteButtonGroup = new Composite(tabTratteGroup, SWT.NONE);
tratteButtonGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false,
false));
tratteButtonGroup.setLayout(new GridLayout(2, true));
aggiungiTratta = new Button(tratteButtonGroup, SWT.PUSH);
aggiungiTratta.setText("+");
rimuoviTratta = new Button(tratteButtonGroup, SWT.PUSH);
rimuoviTratta.setText("-");
rimuoviTratta.setEnabled(false);
}
private void createTabellaStazioniTratta() {
tabellaStazioniTratta = new Table(tabTratteGroup, SWT.SINGLE);
tabellaStazioniTratta.setLinesVisible(true);
tabellaStazioniTratta.setHeaderVisible(true);
TableColumn columnstationone = new TableColumn(tabellaStazioniTratta,
SWT.LEFT);
columnstationone.setText("Stazioni");
TableColumn columnstationtwo = new TableColumn(tabellaStazioniTratta,
SWT.LEFT);
columnstationtwo.setText("Distanza");
tabellaStazioniTratta.getColumn(0).setWidth(290);
tabellaStazioniTratta.getColumn(1).setWidth(75);
tabellaStazioniTratta.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
true, true));
}
private void createTabellaTratte() {
tabellaTratte = new Table(tabTratteGroup, SWT.SINGLE);
tabellaTratte.setLinesVisible(true);
tabellaTratte.setHeaderVisible(true);
TableColumn colonnaId = new TableColumn(tabellaTratte, SWT.LEFT);
colonnaId.setText("Id");
colonnaId.setWidth(70);
TableColumn colonnaTratta = new TableColumn(tabellaTratte, SWT.LEFT);
colonnaTratta.setText("Tratta");
colonnaTratta.setWidth(360);
tabellaTratte
.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
loadTabellaTratte();
}
private void loadTabellaTratte() {
tabellaTratte.removeAll();
List<Tratta> tratte = manager.getTratte();
for (Tratta t : tratte) {
TableItem item = new TableItem(tabellaTratte, SWT.NONE);
item.setText(1, t.getNome());
item.setText(0, Integer.toString(t.getId()));
}
}
private void loadTabellaStazioniTratta(TableItem selezione) {
tabellaStazioniTratta.removeAll();
Tratta t = manager.getTratta(selezione.getText(1));
for (StazioneTratta st : t.getStazioniTratta()) {
TableItem item = new TableItem(tabellaStazioniTratta, SWT.NONE);
item.setText(0, st.getStazione().getNome());
item.setText(1, Integer.toString(st.getDistanza()));
}
}
private void orderTabellaStazioniTratta() {
// FIXME non so quale ordinamento non funge, ma crea altri elementi
// invece di ordinare i nuovi
TableItem[] items = tabellaStazioniTratta.getItems();
int[] distanze = new int[items.length];
for (int i = 0; i < items.length; i++) {
distanze[i] = Integer.parseInt(items[i].getText(1));
}
Arrays.sort(distanze);
for (int i = 0; i < items.length; i++) {
for (int j = 0; j < items.length; j++) {
if (distanze[i] == Integer.parseInt(items[j].getText(1))) {
TableItem newitem = new TableItem(tabellaStazioniTratta,
SWT.NONE);
newitem.setText(0, items[j].getText(0));
newitem.setText(1, items[j].getText(1));
break;
}
}
}
tabellaStazioniTratta.remove(0,
tabellaStazioniTratta.indexOf(items[(items.length) - 1]));
}
public void refresh() {
tabellaStazioniTratta.removeAll();
tabellaTratte.removeAll();
loadTabellaTratte();
}
public TabItem getTab() {
return tabTratte;
}
}
| true | true | private void createRimuoviStazioneTrattaListener() {
rimuoviStazioneTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
TableItem selezionetratta = tabellaTratte.getSelection()[0];
TableItem[] selezionestazione = tabellaStazioniTratta
.getSelection();
int idtratta = Integer.parseInt(selezionetratta.getText(1));
String nomestazione = selezionestazione[0].getText(0);
try {
manager.removeStazioneFromTratta(idtratta, nomestazione);
tabellaStazioniTratta.removeAll();
loadTabellaStazioniTratta(selezionetratta);
} catch (PersistenceException e) {
// AlertShell alert = XXX
// new AlertShell(
// "E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
MessageBox alert = new MessageBox(MainShell.getMainShell()
.getShell(), SWT.ICON_ERROR | SWT.OK);
alert.setMessage("E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
alert.open();
return;
}
}
});
}
| private void createRimuoviStazioneTrattaListener() {
rimuoviStazioneTratta.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
TableItem selezionetratta = tabellaTratte.getSelection()[0];
TableItem[] selezionestazione = tabellaStazioniTratta
.getSelection();
int idtratta = Integer.parseInt(selezionetratta.getText(0));
String nomestazione = selezionestazione[0].getText(0);
try {
manager.removeStazioneFromTratta(idtratta, nomestazione);
tabellaStazioniTratta.removeAll();
loadTabellaStazioniTratta(selezionetratta);
} catch (PersistenceException e) {
// AlertShell alert = XXX
// new AlertShell(
// "E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
MessageBox alert = new MessageBox(MainShell.getMainShell()
.getShell(), SWT.ICON_ERROR | SWT.OK);
alert.setMessage("E' impossibile eliminare questa stazione perche' e' fermata di una corsa. Eliminare prima tale corsa.");
alert.open();
return;
}
}
});
}
|
diff --git a/baksmali/src/test/java/org/jf/baksmali/AnalysisTest.java b/baksmali/src/test/java/org/jf/baksmali/AnalysisTest.java
index 9e1b11f0..a3b58254 100644
--- a/baksmali/src/test/java/org/jf/baksmali/AnalysisTest.java
+++ b/baksmali/src/test/java/org/jf/baksmali/AnalysisTest.java
@@ -1,122 +1,123 @@
/*
* Copyright 2013, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.baksmali;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import junit.framework.Assert;
import org.jf.baksmali.Adaptors.ClassDefinition;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.analysis.ClassPath;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.DexFile;
import org.jf.util.IndentingWriter;
import org.junit.Test;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URL;
public class AnalysisTest {
@Test
public void ConstructorTest() throws IOException, URISyntaxException {
runTest("ConstructorTest", true);
}
@Test
public void RegisterEqualityOnMergeTest() throws IOException, URISyntaxException {
runTest("RegisterEqualityOnMergeTest", true);
}
@Test
public void UninitRefIdentityTest() throws IOException, URISyntaxException {
runTest("UninitRefIdentityTest", true);
}
@Test
public void MultipleStartInstructionsTest() throws IOException, URISyntaxException {
runTest("MultipleStartInstructionsTest", true);
}
@Test
public void DuplicateTest() throws IOException, URISyntaxException {
runTest("DuplicateTest", false);
}
@Test
public void LocalTest() throws IOException, URISyntaxException {
runTest("LocalTest", false);
}
public void runTest(String test, boolean registerInfo) throws IOException, URISyntaxException {
String dexFilePath = String.format("%s%sclasses.dex", test, File.separatorChar);
DexFile dexFile = DexFileFactory.loadDexFile(findResource(dexFilePath), 15);
baksmaliOptions options = new baksmaliOptions();
if (registerInfo) {
options.registerInfo = baksmaliOptions.ALL | baksmaliOptions.FULLMERGE;
options.classPath = new ClassPath();
}
for (ClassDef classDef: dexFile.getClasses()) {
StringWriter stringWriter = new StringWriter();
IndentingWriter writer = new IndentingWriter(stringWriter);
ClassDefinition classDefinition = new ClassDefinition(options, classDef);
classDefinition.writeTo(writer);
writer.close();
String className = classDef.getType();
String smaliPath = String.format("%s%s%s.smali", test, File.separatorChar,
className.substring(1, className.length() - 1));
String smaliContents = readResource(smaliPath);
- Assert.assertEquals(smaliContents.replace("\r\n", "\n"), stringWriter.toString().replace("\r\n", "\n"));
+ Assert.assertEquals(smaliContents.replace("\r", "").replace("\n", System.lineSeparator()),
+ stringWriter.toString().replace("\r", "").replace("\n", System.lineSeparator()));
}
}
@Nonnull
private File findResource(String resource) throws URISyntaxException {
URL resUrl = Resources.getResource(resource);
return new File(resUrl.toURI());
}
@Nonnull
private String readResource(String resource) throws URISyntaxException, IOException {
URL url = Resources.getResource(resource);
return Resources.toString(url, Charsets.UTF_8);
}
}
| true | true | public void runTest(String test, boolean registerInfo) throws IOException, URISyntaxException {
String dexFilePath = String.format("%s%sclasses.dex", test, File.separatorChar);
DexFile dexFile = DexFileFactory.loadDexFile(findResource(dexFilePath), 15);
baksmaliOptions options = new baksmaliOptions();
if (registerInfo) {
options.registerInfo = baksmaliOptions.ALL | baksmaliOptions.FULLMERGE;
options.classPath = new ClassPath();
}
for (ClassDef classDef: dexFile.getClasses()) {
StringWriter stringWriter = new StringWriter();
IndentingWriter writer = new IndentingWriter(stringWriter);
ClassDefinition classDefinition = new ClassDefinition(options, classDef);
classDefinition.writeTo(writer);
writer.close();
String className = classDef.getType();
String smaliPath = String.format("%s%s%s.smali", test, File.separatorChar,
className.substring(1, className.length() - 1));
String smaliContents = readResource(smaliPath);
Assert.assertEquals(smaliContents.replace("\r\n", "\n"), stringWriter.toString().replace("\r\n", "\n"));
}
}
| public void runTest(String test, boolean registerInfo) throws IOException, URISyntaxException {
String dexFilePath = String.format("%s%sclasses.dex", test, File.separatorChar);
DexFile dexFile = DexFileFactory.loadDexFile(findResource(dexFilePath), 15);
baksmaliOptions options = new baksmaliOptions();
if (registerInfo) {
options.registerInfo = baksmaliOptions.ALL | baksmaliOptions.FULLMERGE;
options.classPath = new ClassPath();
}
for (ClassDef classDef: dexFile.getClasses()) {
StringWriter stringWriter = new StringWriter();
IndentingWriter writer = new IndentingWriter(stringWriter);
ClassDefinition classDefinition = new ClassDefinition(options, classDef);
classDefinition.writeTo(writer);
writer.close();
String className = classDef.getType();
String smaliPath = String.format("%s%s%s.smali", test, File.separatorChar,
className.substring(1, className.length() - 1));
String smaliContents = readResource(smaliPath);
Assert.assertEquals(smaliContents.replace("\r", "").replace("\n", System.lineSeparator()),
stringWriter.toString().replace("\r", "").replace("\n", System.lineSeparator()));
}
}
|
diff --git a/seam/tests/org.jboss.tools.seam.ui.test/src/org/jboss/tools/seam/ui/test/el/ELExprPartitionerTest.java b/seam/tests/org.jboss.tools.seam.ui.test/src/org/jboss/tools/seam/ui/test/el/ELExprPartitionerTest.java
index eb8b0aed5..f3b782e4b 100644
--- a/seam/tests/org.jboss.tools.seam.ui.test/src/org/jboss/tools/seam/ui/test/el/ELExprPartitionerTest.java
+++ b/seam/tests/org.jboss.tools.seam.ui.test/src/org/jboss/tools/seam/ui/test/el/ELExprPartitionerTest.java
@@ -1,88 +1,88 @@
/*******************************************************************************
* Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Exadel, Inc. and Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.seam.ui.test.el;
import java.util.ArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.resources.IProject;
import org.jboss.tools.jst.text.ext.hyperlink.ELHyperlink;
import org.jboss.tools.jst.text.ext.hyperlink.ELHyperlinkDetector;
import org.jboss.tools.jst.text.ext.test.HyperlinkTestUtil;
import org.jboss.tools.jst.text.ext.test.HyperlinkTestUtil.TestHyperlink;
import org.jboss.tools.jst.text.ext.test.HyperlinkTestUtil.TestRegion;
import org.jboss.tools.test.util.TestProjectProvider;
public class ELExprPartitionerTest extends TestCase {
TestProjectProvider provider = null;
IProject project = null;
boolean makeCopy = false;
private static final String PROJECT_NAME = "numberguess";
private static final String PAGE_NAME = "/web/giveup.jspx";
public static Test suite() {
return new TestSuite(ELExprPartitionerTest.class);
}
public void setUp() throws Exception {
provider = new TestProjectProvider("org.jboss.tools.seam.ui.test", "projects/" + PROJECT_NAME, PROJECT_NAME, makeCopy);
project = provider.getProject();
Throwable exception = null;
assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception);
}
protected void tearDown() throws Exception {
if(provider != null) {
provider.dispose();
}
}
public void testELExprPartitioner() throws Exception{
ArrayList<TestRegion> regionList = new ArrayList<TestRegion>();
- regionList.add(new TestRegion(673, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(673, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(681, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
- regionList.add(new TestRegion(756, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(756, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(764, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
- regionList.add(new TestRegion(863, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(863, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(871, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_start' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(909, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(921, 15, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getRemainingGuesses() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
- regionList.add(new TestRegion(964, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(964, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(972, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_finish' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
- regionList.add(new TestRegion(1022, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(1022, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1030, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_yes' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
- regionList.add(new TestRegion(1091, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
+ regionList.add(new TestRegion(1091, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1099, 8, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_no' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1157, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1169, 12, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getPossibilities() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1237, 13, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Iterator.next() - java.util'")}));
regionList.add(new TestRegion(1252, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Integer.intValue() - java.lang'")}));
HyperlinkTestUtil.checkRegions(project, PAGE_NAME, regionList, new ELHyperlinkDetector());
}
}
| false | true | public void testELExprPartitioner() throws Exception{
ArrayList<TestRegion> regionList = new ArrayList<TestRegion>();
regionList.add(new TestRegion(673, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(681, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(756, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(764, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(863, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(871, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_start' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(909, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(921, 15, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getRemainingGuesses() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(964, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(972, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_finish' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1022, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1030, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_yes' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1091, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1099, 8, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_no' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1157, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1169, 12, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getPossibilities() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1237, 13, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Iterator.next() - java.util'")}));
regionList.add(new TestRegion(1252, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Integer.intValue() - java.lang'")}));
HyperlinkTestUtil.checkRegions(project, PAGE_NAME, regionList, new ELHyperlinkDetector());
}
| public void testELExprPartitioner() throws Exception{
ArrayList<TestRegion> regionList = new ArrayList<TestRegion>();
regionList.add(new TestRegion(673, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(681, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(756, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(764, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'question' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(863, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(871, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_start' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(909, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(921, 15, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getRemainingGuesses() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(964, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(972, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'info_finish' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1022, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1030, 9, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_yes' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1091, 6, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1099, 8, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open property 'button_no' of bundle 'demo.bundle.Messages'", "Messages.properties")}));
regionList.add(new TestRegion(1157, 10, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1169, 12, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'NumberGuess.getPossibilities() - org.jboss.seam.example.numberguess'", "NumberGuess.java")}));
regionList.add(new TestRegion(1237, 13, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Iterator.next() - java.util'")}));
regionList.add(new TestRegion(1252, 7, new TestHyperlink[]{new TestHyperlink(ELHyperlink.class, "Open 'Integer.intValue() - java.lang'")}));
HyperlinkTestUtil.checkRegions(project, PAGE_NAME, regionList, new ELHyperlinkDetector());
}
|
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java
index a5e08896..600528b7 100644
--- a/src/plugins/WebOfTrust/WebOfTrust.java
+++ b/src/plugins/WebOfTrust/WebOfTrust.java
@@ -1,3567 +1,3568 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WebOfTrust;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import plugins.WebOfTrust.Identity.FetchState;
import plugins.WebOfTrust.Identity.IdentityID;
import plugins.WebOfTrust.Score.ScoreID;
import plugins.WebOfTrust.Trust.TrustID;
import plugins.WebOfTrust.exceptions.DuplicateIdentityException;
import plugins.WebOfTrust.exceptions.DuplicateScoreException;
import plugins.WebOfTrust.exceptions.DuplicateTrustException;
import plugins.WebOfTrust.exceptions.InvalidParameterException;
import plugins.WebOfTrust.exceptions.NotInTrustTreeException;
import plugins.WebOfTrust.exceptions.NotTrustedException;
import plugins.WebOfTrust.exceptions.UnknownIdentityException;
import plugins.WebOfTrust.introduction.IntroductionClient;
import plugins.WebOfTrust.introduction.IntroductionPuzzle;
import plugins.WebOfTrust.introduction.IntroductionPuzzleStore;
import plugins.WebOfTrust.introduction.IntroductionServer;
import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle;
import plugins.WebOfTrust.ui.fcp.FCPInterface;
import plugins.WebOfTrust.ui.web.WebInterface;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.defragment.Defragment;
import com.db4o.defragment.DefragmentConfig;
import com.db4o.ext.ExtObjectContainer;
import com.db4o.query.Query;
import com.db4o.reflect.jdk.JdkReflector;
import freenet.keys.FreenetURI;
import freenet.keys.USK;
import freenet.l10n.BaseL10n;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.l10n.PluginL10n;
import freenet.node.RequestClient;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginBaseL10n;
import freenet.pluginmanager.FredPluginFCP;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginReplySender;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.CurrentTimeUTC;
import freenet.support.Logger;
import freenet.support.Logger.LogLevel;
import freenet.support.SimpleFieldSet;
import freenet.support.SizeUtil;
import freenet.support.api.Bucket;
import freenet.support.io.FileUtil;
/**
* A web of trust plugin based on Freenet.
*
* @author xor ([email protected]), Julien Cornuwel ([email protected])
*/
public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned,
FredPluginL10n, FredPluginBaseL10n {
/* Constants */
public static final boolean FAST_DEBUG_MODE = false;
/** The relative path of the plugin on Freenet's web interface */
public static final String SELF_URI = "/WebOfTrust";
/** Package-private method to allow unit tests to bypass some assert()s */
/**
* The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES
* constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected
* from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace.
*/
public static final String WOT_NAME = "WebOfTrust";
public static final String DATABASE_FILENAME = WOT_NAME + ".db4o";
public static final int DATABASE_FORMAT_VERSION = 2;
/**
* The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one
* trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually,
* the Freenet development team provides a list of seed identities - each of them is one of the developers.
*/
private static final String[] SEED_IDENTITIES = new String[] {
"USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor
"USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad
"USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe
// "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM.
"USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel
};
/* References from the node */
/** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */
private PluginRespirator mPR;
private static PluginL10n l10n;
/* References from the plugin itself */
/* Database & configuration of the plugin */
private ExtObjectContainer mDB;
private Configuration mConfig;
private IntroductionPuzzleStore mPuzzleStore;
/** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */
private XMLTransformer mXMLTransformer;
private RequestClient mRequestClient;
/* Worker objects which actually run the plugin */
/**
* Clients can subscribe to certain events such as identity creation, trust changes, etc. with the {@link SubscriptionManager}
*/
private SubscriptionManager mSubscriptionManager;
/**
* Periodically wakes up and inserts any OwnIdentity which needs to be inserted.
*/
private IdentityInserter mInserter;
/**
* Fetches identities when it is told to do so by the plugin:
* - At startup, all known identities are fetched
* - When a new identity is received from a trust list it is fetched
* - When a new identity is received by the IntrouductionServer it is fetched
* - When an identity is manually added it is also fetched.
* - ...
*/
private IdentityFetcher mFetcher;
/**
* Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone
* uploaded solutions for them periodically and adds the new identities if a solution is received.
*/
private IntroductionServer mIntroductionServer;
/**
* Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for
* the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them.
*/
private IntroductionClient mIntroductionClient;
/* Actual data of the WoT */
private boolean mFullScoreComputationNeeded = false;
private boolean mTrustListImportInProgress = false;
/* User interfaces */
private WebInterface mWebInterface;
private FCPInterface mFCPInterface;
/* Statistics */
private int mFullScoreRecomputationCount = 0;
private long mFullScoreRecomputationMilliseconds = 0;
private int mIncrementalScoreRecomputationCount = 0;
private long mIncrementalScoreRecomputationMilliseconds = 0;
/* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */
private static transient volatile boolean logDEBUG = false;
private static transient volatile boolean logMINOR = false;
static {
Logger.registerClass(WebOfTrust.class);
}
public void runPlugin(PluginRespirator myPR) {
try {
Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up...");
/* Catpcha generation needs headless mode on linux */
System.setProperty("java.awt.headless", "true");
mPR = myPR;
/* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures.
/* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */
// cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone"));
mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME));
mConfig = getOrCreateConfig();
if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used.");
mSubscriptionManager = new SubscriptionManager(this);
mPuzzleStore = new IntroductionPuzzleStore(this);
// Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing.
upgradeDB();
mXMLTransformer = new XMLTransformer(this);
mRequestClient = new RequestClient() {
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
throw new UnsupportedOperationException();
}
public boolean realTimeFlag() {
return false;
}
};
mInserter = new IdentityInserter(this);
mFetcher = new IdentityFetcher(this, getPluginRespirator());
// We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway,
// if the user does not read his logs there is no need to check the integrity.
// TODO: Do this once every few startups and notify the user in the web ui if errors are found.
if(logDEBUG)
verifyDatabaseIntegrity();
// TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs.
verifyAndCorrectStoredScores();
// Database is up now, integrity is checked. We can start to actually do stuff
// TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month
//backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup"));
mSubscriptionManager.start();
createSeedIdentities();
Logger.normal(this, "Starting fetches of all identities...");
synchronized(this) {
synchronized(mFetcher) {
for(Identity identity : getAllIdentities()) {
if(shouldFetchIdentity(identity)) {
try {
mFetcher.fetch(identity.getID());
}
catch(Exception e) {
Logger.error(this, "Fetching identity failed!", e);
}
}
}
}
}
mInserter.start();
mIntroductionServer = new IntroductionServer(this, mFetcher);
mIntroductionServer.start();
mIntroductionClient = new IntroductionClient(this);
mIntroductionClient.start();
mWebInterface = new WebInterface(this, SELF_URI);
mFCPInterface = new FCPInterface(this);
Logger.normal(this, "Web Of Trust plugin starting up completed.");
}
catch(RuntimeException e){
Logger.error(this, "Error during startup", e);
/* We call it so the database is properly closed */
terminate();
throw e;
}
}
/**
* Constructor for being used by the node and unit tests. Does not do anything.
*/
public WebOfTrust() {
}
/**
* Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc.
* For use by the unit tests to be able to run WoT without a node.
* @param databaseFilename The filename of the database.
*/
public WebOfTrust(String databaseFilename) {
mDB = openDatabase(new File(databaseFilename));
mConfig = getOrCreateConfig();
if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() +
"; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION);
mPuzzleStore = new IntroductionPuzzleStore(this);
mSubscriptionManager = new SubscriptionManager(this);
mFetcher = new IdentityFetcher(this, null);
}
private File getUserDataDirectory() {
final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME);
if(!wotDirectory.exists() && !wotDirectory.mkdir())
throw new RuntimeException("Unable to create directory " + wotDirectory);
return wotDirectory;
}
private com.db4o.config.Configuration getNewDatabaseConfiguration() {
com.db4o.config.Configuration cfg = Db4o.newConfiguration();
// Required config options:
cfg.reflectWith(new JdkReflector(getPluginClassLoader()));
// TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works.
// Ideally, we would benchmark both 0 and 1 and make it configurable.
cfg.activationDepth(1);
cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this).
Logger.normal(this, "Default activation depth: " + cfg.activationDepth());
cfg.exceptionsOnNotStorable(true);
// The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it.
cfg.automaticShutDown(false);
// Performance config options:
cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them
cfg.classActivationDepthConfigurable(false);
// Registration of indices (also performance)
// ATTENTION: Also update cloneDatabase() when adding new classes!
@SuppressWarnings("unchecked")
final Class<? extends Persistent>[] persistentClasses = new Class[] {
Configuration.class,
Identity.class,
OwnIdentity.class,
Trust.class,
Score.class,
IdentityFetcher.IdentityFetcherCommand.class,
IdentityFetcher.AbortFetchCommand.class,
IdentityFetcher.StartFetchCommand.class,
IdentityFetcher.UpdateEditionHintCommand.class,
SubscriptionManager.Subscription.class,
SubscriptionManager.IdentitiesSubscription.class,
SubscriptionManager.ScoresSubscription.class,
SubscriptionManager.TrustsSubscription.class,
SubscriptionManager.Notification.class,
SubscriptionManager.InitialSynchronizationNotification.class,
SubscriptionManager.IdentityChangedNotification.class,
SubscriptionManager.ScoreChangedNotification.class,
SubscriptionManager.TrustChangedNotification.class,
IntroductionPuzzle.class,
OwnIntroductionPuzzle.class
};
for(Class<? extends Persistent> clazz : persistentClasses) {
boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null;
// TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling
// them only for the classes where we need them does not cause any harm.
classHasIndex = true;
if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex);
// TODO: Make very sure that it has no negative side effects if we disable class indices for some classes
// Maybe benchmark in comparison to a database which has class indices enabled for ALL classes.
cfg.objectClass(clazz).indexed(classHasIndex);
// Check the class' fields for @IndexedField annotations
for(Field field : clazz.getDeclaredFields()) {
if(field.getAnnotation(Persistent.IndexedField.class) != null) {
if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName());
cfg.objectClass(clazz).objectField(field.getName()).indexed(true);
}
}
// Check whether the class itself has an @IndexedField annotation
final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class);
if(annotation != null) {
for(String fieldName : annotation.names()) {
if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName);
cfg.objectClass(clazz).objectField(fieldName).indexed(true);
}
}
}
// TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one:
// Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it
// We might figure out whether inheritance works by writing a benchmark.
return cfg;
}
private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException {
Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath());
if(mDB != null)
throw new RuntimeException("Database is opened already!");
if(backupFile.exists()) {
try {
FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom);
} catch(IOException e) {
Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath());
}
if(backupFile.renameTo(databaseFile)) {
Logger.warning(this, "Backup restored!");
} else {
throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath());
}
} else {
throw new IOException("Cannot restore backup, it does not exist!");
}
}
private synchronized void defragmentDatabase(File databaseFile) throws IOException {
Logger.normal(this, "Defragmenting database ...");
if(mDB != null)
throw new RuntimeException("Database is opened already!");
if(mPR == null) {
Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting.");
return;
}
final Random random = mPR.getNode().fastWeakRandom;
// Open it first, because defrag will throw if it needs to upgrade the file.
{
final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath());
// Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing
// objects before defragmenting. So we just don't defragment if the database format version has changed.
final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION;
while(!database.close());
if(!canDefragment) {
Logger.normal(this, "Not defragmenting, database format version changed!");
return;
}
if(!databaseFile.exists()) {
Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath());
return;
}
}
final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup");
if(backupFile.exists()) {
Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath());
return;
}
final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp");
FileUtil.secureDelete(tmpFile, random);
/* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs.
/* Reduces memory usage during defragmentation while being slower.
/* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */
final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(),
backupFile.getAbsolutePath()
// ,new BTreeIDMapping(tmpFile.getAbsolutePath())
);
/* Delete classes which are not known to the classloader anymore - We do NOT do this because:
/* - It is buggy and causes exceptions often as of db4o 7.4.63.11890
/* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution.
/* If we need to get rid of certain objects we should do it in the database upgrade code, */
// config.storedClassFilter(new AvailableClassFilter());
config.db4oConfig(getNewDatabaseConfiguration());
try {
Defragment.defrag(config);
} catch (Exception e) {
Logger.error(this, "Defragment failed", e);
try {
restoreDatabaseBackup(databaseFile, backupFile);
return;
} catch(IOException e2) {
Logger.error(this, "Unable to restore backup", e2);
throw new IOException(e);
}
}
final long oldSize = backupFile.length();
final long newSize = databaseFile.length();
if(newSize <= 0) {
Logger.error(this, "Defrag produced an empty file! Trying to restore old database file...");
databaseFile.delete();
try {
restoreDatabaseBackup(databaseFile, backupFile);
} catch(IOException e2) {
Logger.error(this, "Unable to restore backup", e2);
throw new IOException(e2);
}
} else {
final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize));
FileUtil.secureDelete(tmpFile, random);
FileUtil.secureDelete(backupFile, random);
Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> "
+SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)");
}
}
/**
* ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes.
*
* Initializes the plugin's db4o database.
*/
private synchronized ExtObjectContainer openDatabase(File file) {
Logger.normal(this, "Opening database using db4o " + Db4o.version());
if(mDB != null)
throw new RuntimeException("Database is opened already!");
try {
defragmentDatabase(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext();
}
/**
* ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing.
* It doesn't synchronize on the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager because it assumes that they are not being used yet.
* (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit)
*/
@SuppressWarnings("deprecation")
private synchronized void upgradeDB() {
int databaseVersion = mConfig.getDatabaseFormatVersion();
if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION)
return;
// Insert upgrade code here. See Freetalk.java for a skeleton.
if(databaseVersion == 1) {
Logger.normal(this, "Upgrading database version " + databaseVersion);
//synchronized(this) { // Already done at function level
//synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet
//synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet
//synchronized(mSubscriptionManager) { // Normally would be needed for deleteWithoutCommit(Identity) but the SubscriptionManager is not running yet
synchronized(Persistent.transactionLock(mDB)) {
try {
Logger.normal(this, "Generating Score IDs...");
for(Score score : getAllScores()) {
score.generateID();
score.storeWithoutCommit();
}
Logger.normal(this, "Generating Trust IDs...");
for(Trust trust : getAllTrusts()) {
trust.generateID();
trust.storeWithoutCommit();
}
Logger.normal(this, "Searching for identities with mixed up insert/request URIs...");
for(Identity identity : getAllIdentities()) {
try {
USK.create(identity.getRequestURI());
} catch (MalformedURLException e) {
if(identity instanceof OwnIdentity) {
Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" +
"might have been published by solving captchas - the identity could be compromised: " + identity);
} else {
Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity);
deleteWithoutCommit(identity);
}
}
}
mConfig.setDatabaseFormatVersion(++databaseVersion);
mConfig.storeAndCommit();
Logger.normal(this, "Upgraded database to version " + databaseVersion);
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
//}
}
if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION)
throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting "
+ DATABASE_FILENAME + ". Contact the developers if you really need your old data.");
}
/**
* DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE!
*
* Debug function for finding object leaks in the database.
*
* - Deletes all identities in the database - This should delete ALL objects in the database.
* - Then it checks for whether any objects still exist - those are leaks.
*/
private synchronized void checkForDatabaseLeaks() {
Logger.normal(this, "Checking for database leaks... This will delete all identities!");
{
Logger.debug(this, "Checking FetchState leakage...");
final Query query = mDB.query();
query.constrain(FetchState.class);
@SuppressWarnings("unchecked")
ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute();
for(FetchState state : result) {
Logger.debug(this, "Checking " + state);
final Query query2 = mDB.query();
query2.constrain(Identity.class);
query.descend("mCurrentEditionFetchState").constrain(state).identity();
@SuppressWarnings("unchecked")
ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute();
switch(result2.size()) {
case 0:
Logger.error(this, "Found leaked FetchState!");
break;
case 1:
break;
default:
Logger.error(this, "Found re-used FetchState, count: " + result2.size());
break;
}
}
Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size());
}
Logger.normal(this, "Deleting ALL identities...");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
beginTrustListImport();
for(Identity identity : getAllIdentities()) {
deleteWithoutCommit(identity);
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e) {
abortTrustListImport(e);
// abortTrustListImport() does rollback already
// Persistent.checkedRollbackAndThrow(mDB, this, e);
throw e;
}
}
}
}
}
Logger.normal(this, "Deleting ALL identities finished.");
Query query = mDB.query();
query.constrain(Object.class);
@SuppressWarnings("unchecked")
ObjectSet<Object> result = query.execute();
for(Object leak : result) {
Logger.error(this, "Found leaked object: " + leak);
}
Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it.");
}
private synchronized boolean verifyDatabaseIntegrity() {
// Take locks of all objects which deal with persistent stuff because we act upon ALL persistent objects.
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
deleteDuplicateObjects();
deleteOrphanObjects();
Logger.debug(this, "Testing database integrity...");
final Query q = mDB.query();
q.constrain(Persistent.class);
boolean result = true;
for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) {
try {
p.startupDatabaseIntegrityTest();
} catch(Exception e) {
result = false;
try {
Logger.error(this, "Integrity test failed for " + p, e);
} catch(Exception e2) {
Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e);
Logger.error(this, "Exception thrown by toString() was:", e2);
}
}
}
Logger.debug(this, "Database integrity test finished.");
return result;
}
}
}
}
/**
* Does not do proper synchronization! Only use it in single-thread-mode during startup.
*
* Does a backup of the database using db4o's backup mechanism.
*
* This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database.
*/
private synchronized void backupDatabase(File newDatabase) {
Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath());
if(newDatabase.exists())
throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath());
WebOfTrust backup = null;
boolean success = false;
try {
mDB.backup(newDatabase.getAbsolutePath());
if(logDEBUG) {
backup = new WebOfTrust(newDatabase.getAbsolutePath());
// We do not throw to make the clone mechanism more robust in case it is being used for creating backups
Logger.debug(this, "Checking database integrity of clone...");
if(backup.verifyDatabaseIntegrity())
Logger.debug(this, "Checking database integrity of clone finished.");
else
Logger.error(this, "Database integrity check of clone failed!");
Logger.debug(this, "Checking this.equals(clone)...");
if(equals(backup))
Logger.normal(this, "Clone is equal!");
else
Logger.error(this, "Clone is not equal!");
}
success = true;
} finally {
if(backup != null)
backup.terminate();
if(!success)
newDatabase.delete();
}
Logger.normal(this, "Backing up database finished.");
}
/**
* Does not do proper synchronization! Only use it in single-thread-mode during startup.
*
* Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database.
* Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue.
*
* The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch.
* This is useful because the backup mechanism of db4o does nothing but copying the raw file:
* It wouldn't fix databases which cannot be defragmented anymore due to internal corruption.
* - Databases which were cloned by this function CAN be defragmented even if the original database couldn't.
*
* HOWEVER this function uses lots of memory as the whole database is copied into memory.
*/
private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) {
Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath());
if(targetDatabase.exists())
throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath());
WebOfTrust original = null;
WebOfTrust clone = null;
boolean success = false;
try {
original = new WebOfTrust(sourceDatabase.getAbsolutePath());
// We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one.
// - I tried implementing this function in a way where it directly takes the objects from the source database and stores them
// in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting
// in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities.
// FIXME: Clone the Configuration object
final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities());
final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts());
final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores());
for(Identity identity : allIdentities) {
identity.checkedActivate(16);
identity.mWebOfTrust = null;
identity.mDB = null;
}
for(Trust trust : allTrusts) {
trust.checkedActivate(16);
trust.mWebOfTrust = null;
trust.mDB = null;
}
for(Score score : allScores) {
score.checkedActivate(16);
score.mWebOfTrust = null;
score.mDB = null;
}
// We don't clone:
// - Introduction puzzles because we can just download new ones
// - IdentityFetcher commands because they aren't persistent across startups anyway
// - Subscription and Notification objects because subscriptions are also not persistent across startups.
original.terminate();
original = null;
System.gc();
// Now we write out the in-memory copies ...
clone = new WebOfTrust(targetDatabase.getAbsolutePath());
for(Identity identity : allIdentities) {
identity.initializeTransient(clone);
identity.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
for(Trust trust : allTrusts) {
trust.initializeTransient(clone);
trust.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
for(Score score : allScores) {
score.initializeTransient(clone);
score.storeWithoutCommit();
}
Persistent.checkedCommit(clone.getDatabase(), clone);
// And because cloning is a complex operation we do a mandatory database integrity check
Logger.normal(this, "Checking database integrity of clone...");
if(clone.verifyDatabaseIntegrity())
Logger.normal(this, "Checking database integrity of clone finished.");
else
throw new RuntimeException("Database integrity check of clone failed!");
// ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts!
original = new WebOfTrust(sourceDatabase.getAbsolutePath());
Logger.normal(this, "Checking original.equals(clone)...");
if(original.equals(clone))
Logger.normal(this, "Clone is equal!");
else
throw new RuntimeException("Clone is not equal!");
success = true;
} finally {
if(original != null)
original.terminate();
if(clone != null)
clone.terminate();
if(!success)
targetDatabase.delete();
}
Logger.normal(this, "Cloning database finished.");
}
/**
* Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct.
* Incorrect scores are corrected & stored.
*
* The function is synchronized and does a transaction, no outer synchronization is needed.
*/
protected synchronized void verifyAndCorrectStoredScores() {
Logger.normal(this, "Veriying all stored scores ...");
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
Logger.normal(this, "Veriying all stored scores finished.");
}
/**
* Debug function for deleting duplicate identities etc. which might have been created due to bugs :)
*/
private synchronized void deleteDuplicateObjects() {
synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity)
synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity)
synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity)
synchronized(Persistent.transactionLock(mDB)) {
try {
HashSet<String> deleted = new HashSet<String>();
if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ...");
for(Identity identity : getAllIdentities()) {
Query q = mDB.query();
q.constrain(Identity.class);
q.descend("mID").constrain(identity.getID());
q.constrain(identity).identity().not();
ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q);
for(Identity duplicate : duplicates) {
if(deleted.contains(duplicate.getID()) == false) {
Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI());
deleteWithoutCommit(duplicate);
Persistent.checkedCommit(mDB, this);
}
}
deleted.add(identity.getID());
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
} // synchronized(mPuzzleStore) {
// synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ...");
boolean duplicateTrustFound = false;
for(OwnIdentity truster : getAllOwnIdentities()) {
HashSet<String> givenTo = new HashSet<String>();
for(Trust trust : getGivenTrusts(truster)) {
if(givenTo.contains(trust.getTrustee().getID()) == false)
givenTo.add(trust.getTrustee().getID());
else {
Logger.error(this, "Deleting duplicate given trust:" + trust);
removeTrustWithoutCommit(trust);
duplicateTrustFound = true;
}
}
}
if(duplicateTrustFound) {
computeAllScoresWithoutCommit();
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
/* TODO: Also delete duplicate score */
}
/**
* Debug function for deleting trusts or scores of which one of the involved partners is missing.
*/
private synchronized void deleteOrphanObjects() {
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanTrustFound = false;
Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q);
for(Trust trust : orphanTrusts) {
if(trust.getTruster() != null && trust.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust);
continue;
}
Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee());
orphanTrustFound = true;
trust.deleteWithoutCommit();
// No need to update subscriptions as the trust is broken anyway.
}
if(orphanTrustFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanScoresFound = false;
Query q = mDB.query();
q.constrain(Score.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q);
for(Score score : orphanScores) {
if(score.getTruster() != null && score.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score);
continue;
}
Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee());
orphanScoresFound = true;
score.deleteWithoutCommit();
// No need to update subscriptions as the score is broken anyway.
}
if(orphanScoresFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
/**
* Warning: This function is not synchronized, use it only in single threaded mode.
* @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist.
*/
@SuppressWarnings("deprecation")
private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) {
final Query query = database.query();
query.constrain(Configuration.class);
@SuppressWarnings("unchecked")
ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute();
switch(result.size()) {
case 1: {
final Configuration config = (Configuration)result.next();
config.initializeTransient(wot, database);
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
return config.getDatabaseFormatVersion();
}
default:
return -1;
}
}
/**
* Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists.
* @return The config object.
*/
private synchronized Configuration getOrCreateConfig() {
final Query query = mDB.query();
query.constrain(Configuration.class);
final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query);
switch(result.size()) {
case 1: {
final Configuration config = result.next();
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
config.setDefaultValues(false);
config.storeAndCommit();
return config;
}
case 0: {
final Configuration config = new Configuration(this);
config.initializeTransient(this);
config.storeAndCommit();
return config;
}
default:
throw new RuntimeException("Multiple config objects found: " + result.size());
}
}
/** Capacity is the maximum amount of points an identity can give to an other by trusting it.
*
* Values choice :
* Advogato Trust metric recommends that values decrease by rounded 2.5 times.
* This makes sense, making the need of 3 N+1 ranked people to overpower
* the trust given by a N ranked identity.
*
* Number of ranks choice :
* When someone creates a fresh identity, he gets the seed identity at
* rank 1 and freenet developpers at rank 2. That means that
* he will see people that were :
* - given 7 trust by freenet devs (rank 2)
* - given 17 trust by rank 3
* - given 50 trust by rank 4
* - given 100 trust by rank 5 and above.
* This makes the range small enough to avoid a newbie
* to even see spam, and large enough to make him see a reasonnable part
* of the community right out-of-the-box.
* Of course, as soon as he will start to give trust, he will put more
* people at rank 1 and enlarge his WoT.
*/
protected static final int capacities[] = {
100,// Rank 0 : Own identities
40, // Rank 1 : Identities directly trusted by ownIdenties
16, // Rank 2 : Identities trusted by rank 1 identities
6, // So on...
2,
1 // Every identity above rank 5 can give 1 point
}; // Identities with negative score have zero capacity
/**
* Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much
* trust points an identity can add to the score of identities which it has assigned trust values to.
* The higher the rank of an identity, the less is it's capacity.
*
* If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less
* than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0.
*
* If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value:
* The decision of the truster should always overpower the view of remote identities.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed
* @param trustee The {@link Identity} of which the capacity shall be computed.
* @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust,
* - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view.
*/
private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) {
if(truster == trustee)
return 100;
try {
// FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually
// need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert.
if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit.
assert(rank == Integer.MAX_VALUE);
return 0;
}
} catch(NotTrustedException e) { }
if(rank == -1 || rank == Integer.MAX_VALUE)
return 0;
return (rank < capacities.length) ? capacities[rank] : 1;
}
/**
* Reference-implementation of score computation. This means:<br />
* - It is not used by the real WoT code because its slow<br />
* - It is used by unit tests (and WoT) to check whether the real implementation works<br />
* - It is the function which you should read if you want to understand how WoT works.<br />
*
* Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br />
*
* There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br />
*
* Further, rank values are shortest paths and the path-finding algorithm is not executed from the source
* to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path.
* Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database
* and affect many others. So it is useful to have this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}}
* </code>
*
* @return True if all stored scores were correct. False if there were any errors in stored scores.
*/
protected boolean computeAllScoresWithoutCommit() {
if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
boolean returnValue = true;
final ObjectSet<Identity> allIdentities = getAllIdentities();
// Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity.
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
// At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner.
// An identity is visible if there is a trust chain from the owner to it.
// The rank is the distance in trust steps from the treeOwner.
// So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on.
final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2);
// Compute the rank values
{
// For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters.
// The inner loop then pulls out one unprocessed identity and computes the rank of its trustees:
// All trustees which have received positive (> 0) trust will get his rank + 1
// Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE.
// Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all.
// Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none.
//
// Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value:
// The decision of the own identity shall not be overpowered by the view of the remote identities.
//
// The purpose of differentiation between Integer.MAX_VALUE and -1 is:
// Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing
// them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and
// have a way of telling the user "this identity is not trusted" by keeping a score object of them.
// Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where
// we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank
// - and we never import their trust lists.
// We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved
// introduction puzzles cannot inherit their rank to their trustees.
final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>();
// The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE
try {
Score selfScore = getScore(treeOwner, treeOwner);
if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one
rankValues.put(treeOwner, selfScore.getRank());
unprocessedTrusters.addLast(treeOwner);
} else {
rankValues.put(treeOwner, null);
}
} catch(NotInTrustTreeException e) {
// This only happens in unit tests.
}
while(!unprocessedTrusters.isEmpty()) {
final Identity truster = unprocessedTrusters.removeFirst();
final Integer trusterRank = rankValues.get(truster);
// The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all.
if(trusterRank == null || trusterRank == Integer.MAX_VALUE) {
// (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security)
continue;
}
final int trusteeRank = trusterRank + 1;
for(Trust trust : getGivenTrusts(truster)) {
final Identity trustee = trust.getTrustee();
final Integer oldTrusteeRank = rankValues.get(trustee);
if(oldTrusteeRank == null) { // The trustee was not processed yet
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
else
rankValues.put(trustee, Integer.MAX_VALUE);
} else {
// Breadth first search will process all rank one identities are processed before any rank two identities, etc.
assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank);
if(oldTrusteeRank == Integer.MAX_VALUE) {
// If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not
// given by the tree owner.
try {
final Trust treeOwnerTrust = getTrust(treeOwner, trustee);
assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct?
} catch(NotTrustedException e) {
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
}
}
}
}
}
}
// Rank values of all visible identities are computed now.
// Next step is to compute the scores of all identities
for(Identity target : allIdentities) {
// The score of an identity is the sum of all weighted trust values it has received.
// Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank.
Integer targetScore;
final Integer targetRank = rankValues.get(target);
if(targetRank == null) {
targetScore = null;
} else {
// The treeOwner trusts himself.
if(targetRank == 0) {
targetScore = Integer.MAX_VALUE;
}
else {
// If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score.
try {
targetScore = (int)getTrust(treeOwner, target).getValue();
} catch(NotTrustedException e) {
targetScore = 0;
for(Trust receivedTrust : getReceivedTrusts(target)) {
final Identity truster = receivedTrust.getTruster();
final Integer trusterRank = rankValues.get(truster);
// The capacity is a weight function for trust values which are given from an identity:
// The higher the rank, the less the capacity.
// If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0.
final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1);
targetScore += (receivedTrust.getValue() * capacity) / 100;
}
}
}
}
Score newScore = null;
if(targetScore != null) {
newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank));
}
boolean needToCheckFetchStatus = false;
boolean oldShouldFetch = false;
int oldCapacity = 0;
// Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct.
try {
Score currentStoredScore = getScore(treeOwner, target);
oldCapacity = currentStoredScore.getCapacity();
if(newScore == null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
currentStoredScore.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null);
} else {
if(!newScore.equals(currentStoredScore)) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
final Score oldScore = currentStoredScore.clone();
currentStoredScore.setRank(newScore.getRank());
currentStoredScore.setCapacity(newScore.getCapacity());
currentStoredScore.setValue(newScore.getScore());
currentStoredScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore);
}
}
} catch(NotInTrustTreeException e) {
oldCapacity = 0;
if(newScore != null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
newScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore);
}
}
if(needToCheckFetchStatus) {
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target);
target.markForRefetch();
target.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target);
mFetcher.storeStartFetchCommandWithoutCommit(target);
}
else if(oldShouldFetch && !shouldFetchIdentity(target)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target);
mFetcher.storeAbortFetchCommandWithoutCommit(target);
}
}
}
}
mFullScoreComputationNeeded = false;
++mFullScoreRecomputationCount;
mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
if(logMINOR) {
Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s");
}
return returnValue;
}
private synchronized void createSeedIdentities() {
synchronized(mSubscriptionManager) {
for(String seedURI : SEED_IDENTITIES) {
synchronized(Persistent.transactionLock(mDB)) {
try {
final Identity existingSeed = getIdentityByURI(seedURI);
final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager
if(existingSeed instanceof OwnIdentity) {
final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed;
ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY,
Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT));
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed);
ownExistingSeed.storeAndCommit();
}
else {
try {
existingSeed.setEdition(new FreenetURI(seedURI).getEdition());
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed);
existingSeed.storeAndCommit();
} catch(InvalidParameterException e) {
/* We already have the latest edition stored */
}
}
}
catch (UnknownIdentityException uie) {
try {
final Identity newSeed = new Identity(this, seedURI, null, true);
// We have to explicitly set the edition number because the constructor only considers the given edition as a hint.
newSeed.setEdition(new FreenetURI(seedURI).getEdition());
newSeed.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed);
Persistent.checkedCommit(mDB, this);
} catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
public void terminate() {
if(logDEBUG) Logger.debug(this, "WoT plugin terminating ...");
/* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */
try {
if(mWebInterface != null)
this.mWebInterface.unload();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionClient != null)
mIntroductionClient.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionServer != null)
mIntroductionServer.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mInserter != null)
mInserter.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mFetcher != null)
mFetcher.stop();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mSubscriptionManager != null)
mSubscriptionManager.stop();
} catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mDB != null) {
/* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending.
* If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction.
* - All transactions should be committed after obtaining the lock() on the database. */
synchronized(Persistent.transactionLock(mDB)) {
System.gc();
mDB.rollback();
System.gc();
mDB.close();
}
}
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
if(logDEBUG) Logger.debug(this, "WoT plugin terminated.");
}
/**
* Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>.
*/
public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
mFCPInterface.handle(replysender, params, data, accesstype);
}
/**
* Loads an own or normal identity from the database, querying on its ID.
*
* @param id The ID of the identity to load
* @return The identity matching the supplied ID.
* @throws DuplicateIdentityException if there are more than one identity with this id in the database
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(Identity.class);
query.descend("mID").constrain(id);
final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Gets an OwnIdentity by its ID.
*
* @param id The unique identifier to query an OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if there is now OwnIdentity with that id
*/
public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(OwnIdentity.class);
query.descend("mID").constrain(id);
final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI})
*
* @param uri The requestURI of the identity
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Loads an identity from the database, querying on its requestURI (as String)
*
* @param uri The requestURI of the identity which will be converted to {@link FreenetURI}
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
* @throws MalformedURLException if the requestURI isn't a valid FreenetURI
*/
public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getIdentityByURI(new FreenetURI(uri));
}
/**
* Gets an OwnIdentity by its requestURI (a {@link FreenetURI}).
* The OwnIdentity's unique identifier is extracted from the supplied requestURI.
*
* @param uri The requestURI of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
*/
public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Gets an OwnIdentity by its requestURI (as String).
* The given String is converted to {@link FreenetURI} in order to extract a unique id.
*
* @param uri The requestURI (as String) of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
* @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI
*/
public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getOwnIdentityByURI(new FreenetURI(uri));
}
/**
* Returns all identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database
*/
public ObjectSet<Identity> getAllIdentities() {
final Query query = mDB.query();
query.constrain(Identity.class);
return new Persistent.InitializingObjectSet<Identity>(this, query);
}
public static enum SortOrder {
ByNicknameAscending,
ByNicknameDescending,
ByScoreAscending,
ByScoreDescending,
ByLocalTrustAscending,
ByLocalTrustDescending
}
/**
* Get a filtered and sorted list of identities.
* You have to synchronize on this WoT when calling the function and processing the returned list.
*/
public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) {
Query q = mDB.query();
switch(sortInstruction) {
case ByNicknameAscending:
q.constrain(Identity.class);
q.descend("mNickname").orderAscending();
break;
case ByNicknameDescending:
q.constrain(Identity.class);
q.descend("mNickname").orderDescending();
break;
case ByScoreAscending:
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByScoreDescending:
// TODO: This excludes identities which have no score
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
case ByLocalTrustAscending:
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByLocalTrustDescending:
// TODO: This excludes untrusted identities.
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
}
if(nickFilter != null) {
nickFilter = nickFilter.trim();
if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like();
}
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Identity> getAllNonOwnIdentities() {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently
* modified identities will be at the beginning of the list.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* Used by the IntroductionClient for fetching puzzles from recently modified identities.
*/
public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
/* TODO: As soon as identities announce that they were online every day, uncomment the following line */
/* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */
q.descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all own identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database.
*/
public ObjectSet<OwnIdentity> getAllOwnIdentities() {
final Query q = mDB.query();
q.constrain(OwnIdentity.class);
return new Persistent.InitializingObjectSet<OwnIdentity>(this, q);
}
/**
* DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST!
* IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS:
* - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will.
* - Especially it might be an information leak if the trust values of other OwnIdentities are deleted!
* - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption.
*
* The intended purpose of this function is:
* - To specify which objects have to be dealt with when messing with storage of an identity.
* - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them.
* However, the implementations of those functions might cause leaks by forgetting to delete certain object members.
* If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty.
* You then can check whether the database actually IS empty to test for leakage.
*
* You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function.
*/
private void deleteWithoutCommit(Identity identity) {
// We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport.
// If the caller already handles that for us though, we should not call those function again.
// So we check whether the caller already started an import.
boolean trustListImportWasInProgress = mTrustListImportInProgress;
try {
if(!trustListImportWasInProgress)
beginTrustListImport();
if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ...");
if(logDEBUG) Logger.debug(this, "Deleting received scores...");
for(Score score : getScores(identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
if(identity instanceof OwnIdentity) {
if(logDEBUG) Logger.debug(this, "Deleting given scores...");
for(Score score : getGivenScores((OwnIdentity)identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
}
if(logDEBUG) Logger.debug(this, "Deleting received trusts...");
for(Trust trust : getReceivedTrusts(identity)) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
}
if(logDEBUG) Logger.debug(this, "Deleting given trusts...");
for(Trust givenTrust : getGivenTrusts(identity)) {
givenTrust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null);
// We call computeAllScores anyway so we do not use removeTrustWithoutCommit()
}
mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us.
if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ...");
mPuzzleStore.onIdentityDeletion(identity);
if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command...");
if(mFetcher != null) { // Can be null if we use this function in upgradeDB()
mFetcher.storeAbortFetchCommandWithoutCommit(identity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
}
if(logDEBUG) Logger.debug(this, "Deleting the identity...");
identity.deleteWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null);
if(!trustListImportWasInProgress)
finishTrustListImport();
}
catch(RuntimeException e) {
if(!trustListImportWasInProgress)
abortTrustListImport(e);
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
* Gets the score of this identity in a trust tree.
* Each {@link OwnIdentity} has its own trust tree.
*
* @param truster The owner of the trust tree
* @return The {@link Score} of this Identity in the required trust tree
* @throws NotInTrustTreeException if this identity is not in the required trust tree
*/
public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mID").constrain(new ScoreID(truster, trustee).toString());
final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query);
switch(result.size()) {
case 1:
final Score score = result.next();
assert(score.getTruster() == truster);
assert(score.getTrustee() == trustee);
return score;
case 0: throw new NotInTrustTreeException(truster, trustee);
default: throw new DuplicateScoreException(truster, trustee, result.size());
}
}
/**
* Gets a list of all this Identity's Scores.
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
*
* @return An {@link ObjectSet} containing all {@link Score} this Identity has.
*/
public ObjectSet<Score> getScores(final Identity identity) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTrustee").constrain(identity).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Get a list of all scores which the passed own identity has assigned to other identities.
*
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
* @return An {@link ObjectSet} containing all {@link Score} this Identity has given.
*/
public ObjectSet<Score> getGivenScores(final OwnIdentity truster) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets the best score this Identity has in existing trust trees.
*
* @return the best score this Identity has
* @throws NotInTrustTreeException If the identity has no score in any trusttree.
*/
public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException {
int bestScore = Integer.MIN_VALUE;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestScore = Math.max(score.getScore(), bestScore);
return bestScore;
}
/**
* Gets the best capacity this identity has in any trust tree.
* @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0.
*/
public int getBestCapacity(final Identity identity) throws NotInTrustTreeException {
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
return bestCapacity;
}
/**
* Get all scores in the database.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Score> getAllScores() {
final Query query = mDB.query();
query.constrain(Score.class);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Checks whether the given identity should be downloaded.
* @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity.
*/
public boolean shouldFetchIdentity(final Identity identity) {
if(identity instanceof OwnIdentity)
return true;
int bestScore = Integer.MIN_VALUE;
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
return false;
// TODO: Cache the best score of an identity as a member variable.
for(Score score : scores) {
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
bestScore = Math.max(score.getScore(), bestScore);
if(bestCapacity > 0 || bestScore >= 0)
return true;
}
return false;
}
/**
* Gets non-own Identities matching a specified score criteria.
* TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The owner of the trust tree, null if you want the trusted identities of all owners.
* @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0
* and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0.
* @return an {@link ObjectSet} containing Scores of the identities that match the criteria
*/
public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) {
final Query query = mDB.query();
query.constrain(Score.class);
if(truster != null)
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").constrain(OwnIdentity.class).not();
/* We include 0 in the list of identities with positive score because solving captchas gives no points to score */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0)
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets {@link Trust} from a specified truster to a specified trustee.
*
* @param truster The identity that gives trust to this Identity
* @param trustee The identity which receives the trust
* @return The trust given to the trustee by the specified truster
* @throws NotTrustedException if the truster doesn't trust the trustee
*/
public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mID").constrain(new TrustID(truster, trustee).toString());
final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query);
switch(result.size()) {
case 1:
final Trust trust = result.next();
assert(trust.getTruster() == truster);
assert(trust.getTrustee() == trustee);
return trust;
case 0: throw new NotTrustedException(truster, trustee);
default: throw new DuplicateTrustException(truster, trustee, result.size());
}
}
/**
* Gets all trusts given by the given truster.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster.
* The result is sorted descending by the time we last fetched the trusted identity.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets given trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The identity which given the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster in a trust list with a different edition than the passed in one.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) {
final Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mTrusterTrustListEdition").constrain(edition).not();
return new Persistent.InitializingObjectSet<Trust>(this, q);
}
/**
* Gets all trusts received by the given trustee.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets received trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param trustee The identity which has received the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getAllTrusts() {
final Query query = mDB.query();
query.constrain(Trust.class);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gives some {@link Trust} to another Identity.
* It creates or updates an existing Trust object and make the trustee compute its {@link Score}.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster The Identity that gives the trust
* @param trustee The Identity that receives the trust
* @param newValue Numeric value of the trust
* @param newComment A comment to explain the given value
* @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values.
*/
protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
try { // Check if we are updating an existing trust value
final Trust trust = getTrust(truster, trustee);
final Trust oldTrust = trust.clone();
trust.trusterEditionUpdated();
trust.setComment(newComment);
trust.storeWithoutCommit();
if(trust.getValue() != newValue) {
trust.setValue(newValue);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust);
if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(oldTrust, trust);
}
} catch (NotTrustedException e) {
final Trust trust = new Trust(this, truster, trustee, newValue, newComment);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust);
if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(null, trust);
}
truster.updated();
truster.storeWithoutCommit();
// TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't.
// As soon as we have notification-coalescing we might do it.
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster);
}
/**
* Only for being used by WoT internally and by unit tests!
*
* You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function.
*/
void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
setTrustWithoutCommit(truster, trustee, newValue, newComment);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Deletes a trust object.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster
* @param trustee
*/
protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) {
try {
try {
removeTrustWithoutCommit(getTrust(truster, trustee));
} catch (NotTrustedException e) {
Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname());
}
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
*/
protected void removeTrustWithoutCommit(Trust trust) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
updateScoresWithoutCommit(trust, null);
}
/**
* Initializes this OwnIdentity's trust tree without commiting the transaction.
* Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities.
*
* The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }
*
* @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen)
*/
private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException {
try {
getScore(identity, identity);
Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity);
return;
} catch (NotInTrustTreeException e) {
final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100);
score.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score);
}
}
/**
* Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified
* trust tree.
*
* @param truster The OwnIdentity that owns the trust tree
* @param trustee The identity for which the score shall be computed.
* @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster.
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return Integer.MAX_VALUE;
int value = 0;
try {
return getTrust(truster, trustee).getValue();
}
catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
final Score trusterScore = getScore(truster, trust.getTruster());
value += ( trust.getValue() * trusterScore.getCapacity() ) / 100;
} catch (NotInTrustTreeException e) {}
}
return value;
}
/**
* Computes the trustees's rank in the trust tree of the truster.
* It gets its best ranked non-zero-capacity truster's rank, plus one.
* If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite).
* If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1.
*
* If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the
* tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision).
*
* The purpose of differentiation between Integer.MAX_VALUE and -1 is:
* Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them
* in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the
* user "this identity is not trusted" by keeping a score object of them.
* Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we
* hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and
* we never download their trust lists.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The OwnIdentity that owns the trust tree
* @return The new Rank if this Identity
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return 0;
int rank = -1;
try {
Trust treeOwnerTrust = getTrust(truster, trustee);
if(treeOwnerTrust.getValue() > 0)
return 1;
else
return Integer.MAX_VALUE;
} catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
Score score = getScore(truster, trust.getTruster());
if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank
// A truster only gives his rank to a trustee if he has assigned a strictly positive trust value
if(trust.getValue() > 0 ) {
// We give the rank to the trustee if it is better than its current rank or he has no rank yet.
if(rank == -1 || score.getRank() < rank)
rank = score.getRank();
} else {
// If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster.
if(rank == -1)
rank = Integer.MAX_VALUE;
}
}
} catch (NotInTrustTreeException e) {}
}
if(rank == -1)
return -1;
else if(rank == Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return rank+1;
}
/**
* Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress.
* This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called.
*
* ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)}
* for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}}
* </code>
*/
protected void beginTrustListImport() {
if(logMINOR) Logger.minor(this, "beginTrustListImport()");
if(mTrustListImportInProgress) {
abortTrustListImport(new RuntimeException("There was already a trust list import in progress!"));
mFullScoreComputationNeeded = true;
computeAllScoresWithoutCommit();
assert(mFullScoreComputationNeeded == false);
}
mTrustListImportInProgress = true;
assert(!mFullScoreComputationNeeded);
assert(computeAllScoresWithoutCommit()); // The database is intact before the import
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
+ * synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already }
- * }}}
+ * }}}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file.
* @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file.
*/
protected void abortTrustListImport(Exception e, LogLevel logLevel) {
if(logMINOR) Logger.minor(this, "abortTrustListImport()");
assert(mTrustListImportInProgress);
mTrustListImportInProgress = false;
mFullScoreComputationNeeded = false;
Persistent.checkedRollback(mDB, this, e, logLevel);
assert(computeAllScoresWithoutCommit()); // Test rollback.
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR}
*/
protected void abortTrustListImport(Exception e) {
abortTrustListImport(e, Logger.LogLevel.ERROR);
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Finishes the import of the current trust list and performs score computation.
*
* ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it!
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*/
protected void finishTrustListImport() {
if(logMINOR) Logger.minor(this, "finishTrustListImport()");
if(!mTrustListImportInProgress) {
Logger.error(this, "There was no trust list import in progress!");
return;
}
if(mFullScoreComputationNeeded) {
computeAllScoresWithoutCommit();
assert(!mFullScoreComputationNeeded); // It properly clears the flag
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable
}
else
assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked.
mTrustListImportInProgress = false;
}
/**
* Updates all trust trees which are affected by the given modified score.
* For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()}
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; }
* }}}
*/
private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) {
if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
// We only include the time measurement if we actually do something.
// If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included.
boolean includeMeasurement = false;
final boolean trustWasCreated = (oldTrust == null);
final boolean trustWasDeleted = (newTrust == null);
final boolean trustWasModified = !trustWasCreated && !trustWasDeleted;
if(trustWasCreated && trustWasDeleted)
throw new NullPointerException("No old/new trust specified.");
if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster())
throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee())
throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
// We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values
// which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best
// rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity
// then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because
// the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank.
if(trustWasDeleted) {
mFullScoreComputationNeeded = true;
}
if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) {
includeMeasurement = true;
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
try {
// Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score.
if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0)
continue;
} catch(NotInTrustTreeException e) {
continue;
}
// See explanation above "We cannot iteratively REMOVE an inherited rank..."
if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) {
mFullScoreComputationNeeded = true;
break;
}
final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>();
unprocessedEdges.add(newTrust);
while(!unprocessedEdges.isEmpty()) {
final Trust trust = unprocessedEdges.removeFirst();
final Identity trustee = trust.getTrustee();
if(trustee == treeOwner)
continue;
Score currentStoredTrusteeScore;
boolean scoreExistedBefore;
try {
currentStoredTrusteeScore = getScore(treeOwner, trustee);
scoreExistedBefore = true;
} catch(NotInTrustTreeException e) {
scoreExistedBefore = false;
currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0);
}
final Score oldScore = currentStoredTrusteeScore.clone();
boolean oldShouldFetch = shouldFetchIdentity(trustee);
final int newScoreValue = computeScoreValue(treeOwner, trustee);
final int newRank = computeRank(treeOwner, trustee);
final int newCapacity = computeCapacity(treeOwner, trustee, newRank);
final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity);
// Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value,
// the rank and capacity are always computed based on the trust value of the own identity so we must also check this here:
if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank
&& (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore
mFullScoreComputationNeeded = true;
break;
}
if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) {
mFullScoreComputationNeeded = true;
break;
}
// We are OK to update it now. We must not update the values of the stored score object before determining whether we need
// a full score computation - the full computation needs the old values of the object.
currentStoredTrusteeScore.setValue(newScore.getScore());
currentStoredTrusteeScore.setRank(newScore.getRank());
currentStoredTrusteeScore.setCapacity(newScore.getCapacity());
// Identities should not get into the queue if they have no rank, see the large if() about 20 lines below
assert(currentStoredTrusteeScore.getRank() >= 0);
if(currentStoredTrusteeScore.getRank() >= 0) {
currentStoredTrusteeScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore);
}
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee);
trustee.markForRefetch();
trustee.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee);
mFetcher.storeStartFetchCommandWithoutCommit(trustee);
}
else if(oldShouldFetch && !shouldFetchIdentity(trustee)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee);
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
// If the rank or capacity changed then the trustees might be affected because the could have inherited theirs
if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) {
// If this identity has no capacity or no rank then it cannot affect its trustees:
// (- If it had none and it has none now then there is none which can be inherited, this is obvious)
// - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed
if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) {
// We need to update the trustees of trustee
for(Trust givenTrust : getGivenTrusts(trustee)) {
unprocessedEdges.add(givenTrust);
}
}
}
}
if(mFullScoreComputationNeeded)
break;
}
}
if(includeMeasurement) {
++mIncrementalScoreRecomputationCount;
mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
}
if(logMINOR) {
final String time = includeMeasurement ?
("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s")
: ("Time not measured: Computation was aborted before doing anything.");
if(!mFullScoreComputationNeeded)
Logger.minor(this, "Incremental computation of all Scores finished. " + time);
else
Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time);
}
if(!mTrustListImportInProgress) {
if(mFullScoreComputationNeeded) {
// TODO: Optimization: This uses very much CPU and memory. Write a partial computation function...
// TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT
// keep all objects in memory etc.
computeAllScoresWithoutCommit();
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable
} else {
assert(computeAllScoresWithoutCommit()); // This function worked correctly.
}
} else { // a trust list import is in progress
// We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore
// updateScoresWithoutCommit is called often during import of a single trust list
// assert(computeAllScoresWithoutCommit());
}
}
/* Client interface functions */
public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException {
try {
getIdentityByURI(requestURI);
throw new InvalidParameterException("We already have this identity");
}
catch(UnknownIdentityException e) {
final Identity identity = new Identity(this, requestURI, null, false);
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e2) {
Persistent.checkedRollbackAndThrow(mDB, this, e2);
}
}
// The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher.
// TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust.
Logger.normal(this, "addIdentity(): " + identity);
return identity;
}
}
public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context)
throws MalformedURLException, InvalidParameterException {
FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME);
return createOwnIdentity(keypair[0], nickName, publishTrustList, context);
}
/**
* @param context A context with which you want to use the identity. Null if you want to add it later.
*/
public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName,
boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException {
synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit()
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
OwnIdentity identity;
try {
identity = getOwnIdentityByURI(insertURI);
throw new InvalidParameterException("The URI you specified is already used by the own identity " +
identity.getNickname() + ".");
}
catch(UnknownIdentityException uie) {
identity = new OwnIdentity(this, insertURI, nickName, publishTrustList);
if(context != null)
identity.addContext(context);
if(publishTrustList) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
}
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
initTrustTreeWithoutCommit(identity);
beginTrustListImport();
// Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation.
mFullScoreComputationNeeded = true;
for(String seedURI : SEED_IDENTITIES) {
try {
setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity.");
} catch(UnknownIdentityException e) {
Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e);
}
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
if(mIntroductionClient != null)
mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles.
if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")");
return identity;
}
catch(RuntimeException e) {
abortTrustListImport(e); // Rolls back for us
throw e; // Satisfy the compiler
}
}
}
}
}
}
/**
* This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}.
*
* The {@link OwnIdentity} is not deleted because this would be a security issue:
* If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target
*
* @param id The {@link Identity.IdentityID} of the identity.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID.
*/
public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException {
Logger.normal(this, "deleteOwnIdentity(): Starting... ");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
final OwnIdentity oldIdentity = getOwnIdentityByID(id);
try {
Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity);
// We don't need any score computations to happen (explanation will follow below) so we don't need the following:
/* beginTrustListImport(); */
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
final Identity newIdentity;
try {
newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
} catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
} catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
}
newIdentity.setContexts(oldIdentity.getContexts());
newIdentity.setProperties(oldIdentity.getProperties());
try {
newIdentity.setEdition(oldIdentity.getEdition());
} catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen
throw new RuntimeException(e);
}
// In theory we do not need to re-fetch the current trust list edition:
// The trust list of an own identity is always stored completely in the database, i.e. all trustees exist.
// HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that
// the current edition of the old OwndIdentity was not fetched yet.
// So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well.
if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) {
newIdentity.onFetched(oldIdentity.getLastFetchedDate());
}
// An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already.
newIdentity.storeWithoutCommit();
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust;
try {
newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
}
assert(getScores(oldIdentity).size() == 0);
// Delete all given scores:
// Non-own identities do not assign scores to other identities so we can just delete them.
for(Score oldScore : getGivenScores(oldIdentity)) {
final Identity trustee = oldScore.getTrustee();
final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee);
oldScore.deleteWithoutCommit();
// If the OwnIdentity which we are converting was the only source of trust to the trustee
// of this Score value, the should-fetch state of the trustee might change to false.
if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) {
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
}
assert(getGivenScores(oldIdentity).size() == 0);
// Copy all given trusts:
// We don't have to use the removeTrust/setTrust functions because the score graph does not need updating:
// - To the rating of the converted identity in the score graphs of other own identities it is irrelevant
// whether it is an own identity or not. The rating should never depend on whether it is an own identity!
// - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted
// completely and therefore it does not need to be updated.
for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) {
Trust newGivenTrust;
try {
newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(),
oldGivenTrust.getValue(), oldGivenTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newGivenTrust.equals(oldGivenTrust)); */
oldGivenTrust.deleteWithoutCommit();
newGivenTrust.storeWithoutCommit();
}
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(newIdentity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity);
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
Logger.normal(this, "deleteOwnIdentity(): Finished.");
}
/**
* NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()}
*/
public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException {
Logger.normal(this, "restoreOwnIdentity(): Starting... ");
OwnIdentity identity;
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
long edition = 0;
try {
edition = Math.max(edition, insertFreenetURI.getEdition());
} catch(IllegalStateException e) {
// The user supplied URI did not have an edition specified
}
try { // Try replacing an existing non-own version of the identity with an OwnIdentity
Identity oldIdentity = getIdentityByURI(insertFreenetURI);
if(oldIdentity instanceof OwnIdentity)
throw new InvalidParameterException("There is already an own identity with the given URI pair.");
Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity);
// Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function.
// But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference
// implementation will fail if two identities with the same ID exist.
// This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph
// but we must also store the own version to be able to modify the trust graph.
beginTrustListImport();
// We already have fetched this identity as a stranger's one. We need to update the database.
identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
/* We re-fetch the most recent edition to make sure all trustees are imported */
edition = Math.max(edition, oldIdentity.getEdition());
identity.restoreEdition(edition, oldIdentity.getLastFetchedDate());
identity.setContexts(oldIdentity.getContexts());
identity.setProperties(oldIdentity.getProperties());
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
// Nothing has changed about the actual score so we do not notify.
// mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore);
}
assert(getScores(oldIdentity).size() == 0);
// What we do NOT have to deal with is the given scores of the old identity:
// Given scores do NOT exist for non-own identities, so there are no old ones to update.
// Of cause there WILL be scores because it is an own identity now.
// They will be created automatically when updating the given trusts
// - so thats what we will do now.
// Update all given trusts
for(Trust givenTrust : getGivenTrusts(oldIdentity)) {
// TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could:
// - manually delete the old Trust objects from the database
// - manually store the new trust objects
// - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version
// of setTrustWithoutCommit which deals with that.
// But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit:
// To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make
// it only update the parts of the trust graph which are affected.
// Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests.
removeTrustWithoutCommit(givenTrust);
setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment());
}
// We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit
// which would re-create scores of the old identity. We later call it AFTER deleting the old identity.
/* finishTrustListImport(); */
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
finishTrustListImport();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
} catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it.
identity = new OwnIdentity(this, insertFreenetURI, null, false);
Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity);
identity.restoreEdition(edition, null);
// Store the new identity
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
}
mFetcher.storeStartFetchCommandWithoutCommit(identity);
// This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function
abortTrustListImport(e); // Does rollback for us
throw e;
} else {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
}
Logger.normal(this, "restoreOwnIdentity(): Finished.");
}
public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment)
throws UnknownIdentityException, NumberFormatException, InvalidParameterException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
Identity trustee = getIdentityByID(trusteeID);
setTrust(truster, trustee, value, comment);
}
public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
final Identity trustee = getIdentityByID(trusteeID);
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
removeTrustWithoutCommit(truster, trustee);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Enables or disables the publishing of the trust list of an {@link OwnIdentity}.
* The trust list contains all trust values which the OwnIdentity has assigned to other identities.
*
* @see OwnIdentity#setPublishTrustList(boolean)
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishTrustList Whether to publish the trust list.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}.
*/
public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setPublishTrustList(publishTrustList);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity);
}
/**
* Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}.
*
* If publishIntroductionPuzzles==true adds, if false removes:
* - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT}
* - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT}
*
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishIntroductionPuzzles Whether to publish introduction puzzles.
* @throws UnknownIdentityException If there is no identity with the given ownIdentityID
* @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list.
*/
public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
if(!identity.doesPublishTrustList())
throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!");
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
if(publishIntroductionPuzzles) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
} else {
identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY);
}
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity);
}
public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.addContext(newContext);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeContext(context);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'");
}
public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException {
return getIdentityByID(identityID).getProperty(property);
}
public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setProperty(property, value);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeProperty(property);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'");
}
public String getVersion() {
return Version.getMarketingVersion();
}
public long getRealVersion() {
return Version.getRealVersion();
}
public String getString(String key) {
return getBaseL10n().getString(key);
}
public void setLanguage(LANGUAGE newLanguage) {
WebOfTrust.l10n = new PluginL10n(this, newLanguage);
if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode);
}
public PluginRespirator getPluginRespirator() {
return mPR;
}
public ExtObjectContainer getDatabase() {
return mDB;
}
public Configuration getConfig() {
return mConfig;
}
public SubscriptionManager getSubscriptionManager() {
return mSubscriptionManager;
}
public IdentityFetcher getIdentityFetcher() {
return mFetcher;
}
public XMLTransformer getXMLTransformer() {
return mXMLTransformer;
}
public IntroductionPuzzleStore getIntroductionPuzzleStore() {
return mPuzzleStore;
}
public IntroductionClient getIntroductionClient() {
return mIntroductionClient;
}
protected FCPInterface getFCPInterface() {
return mFCPInterface;
}
public RequestClient getRequestClient() {
return mRequestClient;
}
/**
* This is where our L10n files are stored.
* @return Path of our L10n files.
*/
public String getL10nFilesBasePath() {
return "plugins/WebOfTrust/l10n/";
}
/**
* This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ...
* @return Mask of the L10n files.
*/
public String getL10nFilesMask() {
return "lang_${lang}.l10n";
}
/**
* Override L10n files are stored on the disk, their names should be explicit
* we put here the plugin name, and the "override" indication. Plugin L10n
* override is not implemented in the node yet.
* @return Mask of the override L10n files.
*/
public String getL10nOverrideFilesMask() {
return "WebOfTrust_lang_${lang}.override.l10n";
}
/**
* Get the ClassLoader of this plugin. This is necessary when getting
* resources inside the plugin's Jar, for example L10n files.
* @return ClassLoader object
*/
public ClassLoader getPluginClassLoader() {
return WebOfTrust.class.getClassLoader();
}
/**
* Access to the current L10n data.
*
* @return L10n object.
*/
public BaseL10n getBaseL10n() {
return WebOfTrust.l10n.getBase();
}
public int getNumberOfFullScoreRecomputations() {
return mFullScoreRecomputationCount;
}
public synchronized double getAverageFullScoreRecomputationTime() {
return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000);
}
public int getNumberOfIncrementalScoreRecomputations() {
return mIncrementalScoreRecomputationCount;
}
public synchronized double getAverageIncrementalScoreRecomputationTime() {
return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000);
}
/**
* Tests whether two WoT are equal.
* This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests.
*/
public synchronized boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof WebOfTrust))
return false;
WebOfTrust other = (WebOfTrust)obj;
synchronized(other) {
{ // Compare own identities
final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities();
if(allIdentities.size() != other.getAllOwnIdentities().size())
return false;
for(OwnIdentity identity : allIdentities) {
try {
if(!identity.equals(other.getOwnIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare identities
final ObjectSet<Identity> allIdentities = getAllIdentities();
if(allIdentities.size() != other.getAllIdentities().size())
return false;
for(Identity identity : allIdentities) {
try {
if(!identity.equals(other.getIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare trusts
final ObjectSet<Trust> allTrusts = getAllTrusts();
if(allTrusts.size() != other.getAllTrusts().size())
return false;
for(Trust trust : allTrusts) {
try {
Identity otherTruster = other.getIdentityByID(trust.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID());
if(!trust.equals(other.getTrust(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotTrustedException e) {
return false;
}
}
}
{ // Compare scores
final ObjectSet<Score> allScores = getAllScores();
if(allScores.size() != other.getAllScores().size())
return false;
for(Score score : allScores) {
try {
OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID());
if(!score.equals(other.getScore(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotInTrustTreeException e) {
return false;
}
}
}
}
return true;
}
}
| false | true | private synchronized void deleteDuplicateObjects() {
synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity)
synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity)
synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity)
synchronized(Persistent.transactionLock(mDB)) {
try {
HashSet<String> deleted = new HashSet<String>();
if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ...");
for(Identity identity : getAllIdentities()) {
Query q = mDB.query();
q.constrain(Identity.class);
q.descend("mID").constrain(identity.getID());
q.constrain(identity).identity().not();
ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q);
for(Identity duplicate : duplicates) {
if(deleted.contains(duplicate.getID()) == false) {
Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI());
deleteWithoutCommit(duplicate);
Persistent.checkedCommit(mDB, this);
}
}
deleted.add(identity.getID());
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
} // synchronized(mPuzzleStore) {
// synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ...");
boolean duplicateTrustFound = false;
for(OwnIdentity truster : getAllOwnIdentities()) {
HashSet<String> givenTo = new HashSet<String>();
for(Trust trust : getGivenTrusts(truster)) {
if(givenTo.contains(trust.getTrustee().getID()) == false)
givenTo.add(trust.getTrustee().getID());
else {
Logger.error(this, "Deleting duplicate given trust:" + trust);
removeTrustWithoutCommit(trust);
duplicateTrustFound = true;
}
}
}
if(duplicateTrustFound) {
computeAllScoresWithoutCommit();
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
/* TODO: Also delete duplicate score */
}
/**
* Debug function for deleting trusts or scores of which one of the involved partners is missing.
*/
private synchronized void deleteOrphanObjects() {
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanTrustFound = false;
Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q);
for(Trust trust : orphanTrusts) {
if(trust.getTruster() != null && trust.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust);
continue;
}
Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee());
orphanTrustFound = true;
trust.deleteWithoutCommit();
// No need to update subscriptions as the trust is broken anyway.
}
if(orphanTrustFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanScoresFound = false;
Query q = mDB.query();
q.constrain(Score.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q);
for(Score score : orphanScores) {
if(score.getTruster() != null && score.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score);
continue;
}
Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee());
orphanScoresFound = true;
score.deleteWithoutCommit();
// No need to update subscriptions as the score is broken anyway.
}
if(orphanScoresFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
/**
* Warning: This function is not synchronized, use it only in single threaded mode.
* @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist.
*/
@SuppressWarnings("deprecation")
private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) {
final Query query = database.query();
query.constrain(Configuration.class);
@SuppressWarnings("unchecked")
ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute();
switch(result.size()) {
case 1: {
final Configuration config = (Configuration)result.next();
config.initializeTransient(wot, database);
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
return config.getDatabaseFormatVersion();
}
default:
return -1;
}
}
/**
* Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists.
* @return The config object.
*/
private synchronized Configuration getOrCreateConfig() {
final Query query = mDB.query();
query.constrain(Configuration.class);
final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query);
switch(result.size()) {
case 1: {
final Configuration config = result.next();
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
config.setDefaultValues(false);
config.storeAndCommit();
return config;
}
case 0: {
final Configuration config = new Configuration(this);
config.initializeTransient(this);
config.storeAndCommit();
return config;
}
default:
throw new RuntimeException("Multiple config objects found: " + result.size());
}
}
/** Capacity is the maximum amount of points an identity can give to an other by trusting it.
*
* Values choice :
* Advogato Trust metric recommends that values decrease by rounded 2.5 times.
* This makes sense, making the need of 3 N+1 ranked people to overpower
* the trust given by a N ranked identity.
*
* Number of ranks choice :
* When someone creates a fresh identity, he gets the seed identity at
* rank 1 and freenet developpers at rank 2. That means that
* he will see people that were :
* - given 7 trust by freenet devs (rank 2)
* - given 17 trust by rank 3
* - given 50 trust by rank 4
* - given 100 trust by rank 5 and above.
* This makes the range small enough to avoid a newbie
* to even see spam, and large enough to make him see a reasonnable part
* of the community right out-of-the-box.
* Of course, as soon as he will start to give trust, he will put more
* people at rank 1 and enlarge his WoT.
*/
protected static final int capacities[] = {
100,// Rank 0 : Own identities
40, // Rank 1 : Identities directly trusted by ownIdenties
16, // Rank 2 : Identities trusted by rank 1 identities
6, // So on...
2,
1 // Every identity above rank 5 can give 1 point
}; // Identities with negative score have zero capacity
/**
* Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much
* trust points an identity can add to the score of identities which it has assigned trust values to.
* The higher the rank of an identity, the less is it's capacity.
*
* If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less
* than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0.
*
* If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value:
* The decision of the truster should always overpower the view of remote identities.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed
* @param trustee The {@link Identity} of which the capacity shall be computed.
* @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust,
* - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view.
*/
private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) {
if(truster == trustee)
return 100;
try {
// FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually
// need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert.
if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit.
assert(rank == Integer.MAX_VALUE);
return 0;
}
} catch(NotTrustedException e) { }
if(rank == -1 || rank == Integer.MAX_VALUE)
return 0;
return (rank < capacities.length) ? capacities[rank] : 1;
}
/**
* Reference-implementation of score computation. This means:<br />
* - It is not used by the real WoT code because its slow<br />
* - It is used by unit tests (and WoT) to check whether the real implementation works<br />
* - It is the function which you should read if you want to understand how WoT works.<br />
*
* Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br />
*
* There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br />
*
* Further, rank values are shortest paths and the path-finding algorithm is not executed from the source
* to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path.
* Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database
* and affect many others. So it is useful to have this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}}
* </code>
*
* @return True if all stored scores were correct. False if there were any errors in stored scores.
*/
protected boolean computeAllScoresWithoutCommit() {
if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
boolean returnValue = true;
final ObjectSet<Identity> allIdentities = getAllIdentities();
// Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity.
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
// At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner.
// An identity is visible if there is a trust chain from the owner to it.
// The rank is the distance in trust steps from the treeOwner.
// So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on.
final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2);
// Compute the rank values
{
// For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters.
// The inner loop then pulls out one unprocessed identity and computes the rank of its trustees:
// All trustees which have received positive (> 0) trust will get his rank + 1
// Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE.
// Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all.
// Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none.
//
// Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value:
// The decision of the own identity shall not be overpowered by the view of the remote identities.
//
// The purpose of differentiation between Integer.MAX_VALUE and -1 is:
// Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing
// them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and
// have a way of telling the user "this identity is not trusted" by keeping a score object of them.
// Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where
// we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank
// - and we never import their trust lists.
// We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved
// introduction puzzles cannot inherit their rank to their trustees.
final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>();
// The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE
try {
Score selfScore = getScore(treeOwner, treeOwner);
if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one
rankValues.put(treeOwner, selfScore.getRank());
unprocessedTrusters.addLast(treeOwner);
} else {
rankValues.put(treeOwner, null);
}
} catch(NotInTrustTreeException e) {
// This only happens in unit tests.
}
while(!unprocessedTrusters.isEmpty()) {
final Identity truster = unprocessedTrusters.removeFirst();
final Integer trusterRank = rankValues.get(truster);
// The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all.
if(trusterRank == null || trusterRank == Integer.MAX_VALUE) {
// (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security)
continue;
}
final int trusteeRank = trusterRank + 1;
for(Trust trust : getGivenTrusts(truster)) {
final Identity trustee = trust.getTrustee();
final Integer oldTrusteeRank = rankValues.get(trustee);
if(oldTrusteeRank == null) { // The trustee was not processed yet
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
else
rankValues.put(trustee, Integer.MAX_VALUE);
} else {
// Breadth first search will process all rank one identities are processed before any rank two identities, etc.
assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank);
if(oldTrusteeRank == Integer.MAX_VALUE) {
// If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not
// given by the tree owner.
try {
final Trust treeOwnerTrust = getTrust(treeOwner, trustee);
assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct?
} catch(NotTrustedException e) {
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
}
}
}
}
}
}
// Rank values of all visible identities are computed now.
// Next step is to compute the scores of all identities
for(Identity target : allIdentities) {
// The score of an identity is the sum of all weighted trust values it has received.
// Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank.
Integer targetScore;
final Integer targetRank = rankValues.get(target);
if(targetRank == null) {
targetScore = null;
} else {
// The treeOwner trusts himself.
if(targetRank == 0) {
targetScore = Integer.MAX_VALUE;
}
else {
// If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score.
try {
targetScore = (int)getTrust(treeOwner, target).getValue();
} catch(NotTrustedException e) {
targetScore = 0;
for(Trust receivedTrust : getReceivedTrusts(target)) {
final Identity truster = receivedTrust.getTruster();
final Integer trusterRank = rankValues.get(truster);
// The capacity is a weight function for trust values which are given from an identity:
// The higher the rank, the less the capacity.
// If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0.
final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1);
targetScore += (receivedTrust.getValue() * capacity) / 100;
}
}
}
}
Score newScore = null;
if(targetScore != null) {
newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank));
}
boolean needToCheckFetchStatus = false;
boolean oldShouldFetch = false;
int oldCapacity = 0;
// Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct.
try {
Score currentStoredScore = getScore(treeOwner, target);
oldCapacity = currentStoredScore.getCapacity();
if(newScore == null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
currentStoredScore.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null);
} else {
if(!newScore.equals(currentStoredScore)) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
final Score oldScore = currentStoredScore.clone();
currentStoredScore.setRank(newScore.getRank());
currentStoredScore.setCapacity(newScore.getCapacity());
currentStoredScore.setValue(newScore.getScore());
currentStoredScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore);
}
}
} catch(NotInTrustTreeException e) {
oldCapacity = 0;
if(newScore != null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
newScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore);
}
}
if(needToCheckFetchStatus) {
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target);
target.markForRefetch();
target.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target);
mFetcher.storeStartFetchCommandWithoutCommit(target);
}
else if(oldShouldFetch && !shouldFetchIdentity(target)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target);
mFetcher.storeAbortFetchCommandWithoutCommit(target);
}
}
}
}
mFullScoreComputationNeeded = false;
++mFullScoreRecomputationCount;
mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
if(logMINOR) {
Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s");
}
return returnValue;
}
private synchronized void createSeedIdentities() {
synchronized(mSubscriptionManager) {
for(String seedURI : SEED_IDENTITIES) {
synchronized(Persistent.transactionLock(mDB)) {
try {
final Identity existingSeed = getIdentityByURI(seedURI);
final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager
if(existingSeed instanceof OwnIdentity) {
final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed;
ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY,
Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT));
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed);
ownExistingSeed.storeAndCommit();
}
else {
try {
existingSeed.setEdition(new FreenetURI(seedURI).getEdition());
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed);
existingSeed.storeAndCommit();
} catch(InvalidParameterException e) {
/* We already have the latest edition stored */
}
}
}
catch (UnknownIdentityException uie) {
try {
final Identity newSeed = new Identity(this, seedURI, null, true);
// We have to explicitly set the edition number because the constructor only considers the given edition as a hint.
newSeed.setEdition(new FreenetURI(seedURI).getEdition());
newSeed.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed);
Persistent.checkedCommit(mDB, this);
} catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
public void terminate() {
if(logDEBUG) Logger.debug(this, "WoT plugin terminating ...");
/* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */
try {
if(mWebInterface != null)
this.mWebInterface.unload();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionClient != null)
mIntroductionClient.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionServer != null)
mIntroductionServer.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mInserter != null)
mInserter.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mFetcher != null)
mFetcher.stop();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mSubscriptionManager != null)
mSubscriptionManager.stop();
} catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mDB != null) {
/* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending.
* If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction.
* - All transactions should be committed after obtaining the lock() on the database. */
synchronized(Persistent.transactionLock(mDB)) {
System.gc();
mDB.rollback();
System.gc();
mDB.close();
}
}
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
if(logDEBUG) Logger.debug(this, "WoT plugin terminated.");
}
/**
* Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>.
*/
public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
mFCPInterface.handle(replysender, params, data, accesstype);
}
/**
* Loads an own or normal identity from the database, querying on its ID.
*
* @param id The ID of the identity to load
* @return The identity matching the supplied ID.
* @throws DuplicateIdentityException if there are more than one identity with this id in the database
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(Identity.class);
query.descend("mID").constrain(id);
final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Gets an OwnIdentity by its ID.
*
* @param id The unique identifier to query an OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if there is now OwnIdentity with that id
*/
public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(OwnIdentity.class);
query.descend("mID").constrain(id);
final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI})
*
* @param uri The requestURI of the identity
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Loads an identity from the database, querying on its requestURI (as String)
*
* @param uri The requestURI of the identity which will be converted to {@link FreenetURI}
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
* @throws MalformedURLException if the requestURI isn't a valid FreenetURI
*/
public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getIdentityByURI(new FreenetURI(uri));
}
/**
* Gets an OwnIdentity by its requestURI (a {@link FreenetURI}).
* The OwnIdentity's unique identifier is extracted from the supplied requestURI.
*
* @param uri The requestURI of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
*/
public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Gets an OwnIdentity by its requestURI (as String).
* The given String is converted to {@link FreenetURI} in order to extract a unique id.
*
* @param uri The requestURI (as String) of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
* @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI
*/
public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getOwnIdentityByURI(new FreenetURI(uri));
}
/**
* Returns all identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database
*/
public ObjectSet<Identity> getAllIdentities() {
final Query query = mDB.query();
query.constrain(Identity.class);
return new Persistent.InitializingObjectSet<Identity>(this, query);
}
public static enum SortOrder {
ByNicknameAscending,
ByNicknameDescending,
ByScoreAscending,
ByScoreDescending,
ByLocalTrustAscending,
ByLocalTrustDescending
}
/**
* Get a filtered and sorted list of identities.
* You have to synchronize on this WoT when calling the function and processing the returned list.
*/
public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) {
Query q = mDB.query();
switch(sortInstruction) {
case ByNicknameAscending:
q.constrain(Identity.class);
q.descend("mNickname").orderAscending();
break;
case ByNicknameDescending:
q.constrain(Identity.class);
q.descend("mNickname").orderDescending();
break;
case ByScoreAscending:
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByScoreDescending:
// TODO: This excludes identities which have no score
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
case ByLocalTrustAscending:
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByLocalTrustDescending:
// TODO: This excludes untrusted identities.
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
}
if(nickFilter != null) {
nickFilter = nickFilter.trim();
if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like();
}
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Identity> getAllNonOwnIdentities() {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently
* modified identities will be at the beginning of the list.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* Used by the IntroductionClient for fetching puzzles from recently modified identities.
*/
public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
/* TODO: As soon as identities announce that they were online every day, uncomment the following line */
/* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */
q.descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all own identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database.
*/
public ObjectSet<OwnIdentity> getAllOwnIdentities() {
final Query q = mDB.query();
q.constrain(OwnIdentity.class);
return new Persistent.InitializingObjectSet<OwnIdentity>(this, q);
}
/**
* DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST!
* IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS:
* - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will.
* - Especially it might be an information leak if the trust values of other OwnIdentities are deleted!
* - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption.
*
* The intended purpose of this function is:
* - To specify which objects have to be dealt with when messing with storage of an identity.
* - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them.
* However, the implementations of those functions might cause leaks by forgetting to delete certain object members.
* If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty.
* You then can check whether the database actually IS empty to test for leakage.
*
* You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function.
*/
private void deleteWithoutCommit(Identity identity) {
// We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport.
// If the caller already handles that for us though, we should not call those function again.
// So we check whether the caller already started an import.
boolean trustListImportWasInProgress = mTrustListImportInProgress;
try {
if(!trustListImportWasInProgress)
beginTrustListImport();
if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ...");
if(logDEBUG) Logger.debug(this, "Deleting received scores...");
for(Score score : getScores(identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
if(identity instanceof OwnIdentity) {
if(logDEBUG) Logger.debug(this, "Deleting given scores...");
for(Score score : getGivenScores((OwnIdentity)identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
}
if(logDEBUG) Logger.debug(this, "Deleting received trusts...");
for(Trust trust : getReceivedTrusts(identity)) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
}
if(logDEBUG) Logger.debug(this, "Deleting given trusts...");
for(Trust givenTrust : getGivenTrusts(identity)) {
givenTrust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null);
// We call computeAllScores anyway so we do not use removeTrustWithoutCommit()
}
mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us.
if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ...");
mPuzzleStore.onIdentityDeletion(identity);
if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command...");
if(mFetcher != null) { // Can be null if we use this function in upgradeDB()
mFetcher.storeAbortFetchCommandWithoutCommit(identity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
}
if(logDEBUG) Logger.debug(this, "Deleting the identity...");
identity.deleteWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null);
if(!trustListImportWasInProgress)
finishTrustListImport();
}
catch(RuntimeException e) {
if(!trustListImportWasInProgress)
abortTrustListImport(e);
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
* Gets the score of this identity in a trust tree.
* Each {@link OwnIdentity} has its own trust tree.
*
* @param truster The owner of the trust tree
* @return The {@link Score} of this Identity in the required trust tree
* @throws NotInTrustTreeException if this identity is not in the required trust tree
*/
public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mID").constrain(new ScoreID(truster, trustee).toString());
final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query);
switch(result.size()) {
case 1:
final Score score = result.next();
assert(score.getTruster() == truster);
assert(score.getTrustee() == trustee);
return score;
case 0: throw new NotInTrustTreeException(truster, trustee);
default: throw new DuplicateScoreException(truster, trustee, result.size());
}
}
/**
* Gets a list of all this Identity's Scores.
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
*
* @return An {@link ObjectSet} containing all {@link Score} this Identity has.
*/
public ObjectSet<Score> getScores(final Identity identity) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTrustee").constrain(identity).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Get a list of all scores which the passed own identity has assigned to other identities.
*
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
* @return An {@link ObjectSet} containing all {@link Score} this Identity has given.
*/
public ObjectSet<Score> getGivenScores(final OwnIdentity truster) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets the best score this Identity has in existing trust trees.
*
* @return the best score this Identity has
* @throws NotInTrustTreeException If the identity has no score in any trusttree.
*/
public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException {
int bestScore = Integer.MIN_VALUE;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestScore = Math.max(score.getScore(), bestScore);
return bestScore;
}
/**
* Gets the best capacity this identity has in any trust tree.
* @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0.
*/
public int getBestCapacity(final Identity identity) throws NotInTrustTreeException {
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
return bestCapacity;
}
/**
* Get all scores in the database.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Score> getAllScores() {
final Query query = mDB.query();
query.constrain(Score.class);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Checks whether the given identity should be downloaded.
* @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity.
*/
public boolean shouldFetchIdentity(final Identity identity) {
if(identity instanceof OwnIdentity)
return true;
int bestScore = Integer.MIN_VALUE;
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
return false;
// TODO: Cache the best score of an identity as a member variable.
for(Score score : scores) {
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
bestScore = Math.max(score.getScore(), bestScore);
if(bestCapacity > 0 || bestScore >= 0)
return true;
}
return false;
}
/**
* Gets non-own Identities matching a specified score criteria.
* TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The owner of the trust tree, null if you want the trusted identities of all owners.
* @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0
* and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0.
* @return an {@link ObjectSet} containing Scores of the identities that match the criteria
*/
public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) {
final Query query = mDB.query();
query.constrain(Score.class);
if(truster != null)
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").constrain(OwnIdentity.class).not();
/* We include 0 in the list of identities with positive score because solving captchas gives no points to score */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0)
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets {@link Trust} from a specified truster to a specified trustee.
*
* @param truster The identity that gives trust to this Identity
* @param trustee The identity which receives the trust
* @return The trust given to the trustee by the specified truster
* @throws NotTrustedException if the truster doesn't trust the trustee
*/
public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mID").constrain(new TrustID(truster, trustee).toString());
final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query);
switch(result.size()) {
case 1:
final Trust trust = result.next();
assert(trust.getTruster() == truster);
assert(trust.getTrustee() == trustee);
return trust;
case 0: throw new NotTrustedException(truster, trustee);
default: throw new DuplicateTrustException(truster, trustee, result.size());
}
}
/**
* Gets all trusts given by the given truster.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster.
* The result is sorted descending by the time we last fetched the trusted identity.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets given trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The identity which given the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster in a trust list with a different edition than the passed in one.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) {
final Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mTrusterTrustListEdition").constrain(edition).not();
return new Persistent.InitializingObjectSet<Trust>(this, q);
}
/**
* Gets all trusts received by the given trustee.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets received trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param trustee The identity which has received the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getAllTrusts() {
final Query query = mDB.query();
query.constrain(Trust.class);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gives some {@link Trust} to another Identity.
* It creates or updates an existing Trust object and make the trustee compute its {@link Score}.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster The Identity that gives the trust
* @param trustee The Identity that receives the trust
* @param newValue Numeric value of the trust
* @param newComment A comment to explain the given value
* @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values.
*/
protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
try { // Check if we are updating an existing trust value
final Trust trust = getTrust(truster, trustee);
final Trust oldTrust = trust.clone();
trust.trusterEditionUpdated();
trust.setComment(newComment);
trust.storeWithoutCommit();
if(trust.getValue() != newValue) {
trust.setValue(newValue);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust);
if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(oldTrust, trust);
}
} catch (NotTrustedException e) {
final Trust trust = new Trust(this, truster, trustee, newValue, newComment);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust);
if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(null, trust);
}
truster.updated();
truster.storeWithoutCommit();
// TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't.
// As soon as we have notification-coalescing we might do it.
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster);
}
/**
* Only for being used by WoT internally and by unit tests!
*
* You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function.
*/
void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
setTrustWithoutCommit(truster, trustee, newValue, newComment);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Deletes a trust object.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster
* @param trustee
*/
protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) {
try {
try {
removeTrustWithoutCommit(getTrust(truster, trustee));
} catch (NotTrustedException e) {
Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname());
}
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
*/
protected void removeTrustWithoutCommit(Trust trust) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
updateScoresWithoutCommit(trust, null);
}
/**
* Initializes this OwnIdentity's trust tree without commiting the transaction.
* Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities.
*
* The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }
*
* @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen)
*/
private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException {
try {
getScore(identity, identity);
Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity);
return;
} catch (NotInTrustTreeException e) {
final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100);
score.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score);
}
}
/**
* Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified
* trust tree.
*
* @param truster The OwnIdentity that owns the trust tree
* @param trustee The identity for which the score shall be computed.
* @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster.
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return Integer.MAX_VALUE;
int value = 0;
try {
return getTrust(truster, trustee).getValue();
}
catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
final Score trusterScore = getScore(truster, trust.getTruster());
value += ( trust.getValue() * trusterScore.getCapacity() ) / 100;
} catch (NotInTrustTreeException e) {}
}
return value;
}
/**
* Computes the trustees's rank in the trust tree of the truster.
* It gets its best ranked non-zero-capacity truster's rank, plus one.
* If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite).
* If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1.
*
* If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the
* tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision).
*
* The purpose of differentiation between Integer.MAX_VALUE and -1 is:
* Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them
* in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the
* user "this identity is not trusted" by keeping a score object of them.
* Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we
* hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and
* we never download their trust lists.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The OwnIdentity that owns the trust tree
* @return The new Rank if this Identity
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return 0;
int rank = -1;
try {
Trust treeOwnerTrust = getTrust(truster, trustee);
if(treeOwnerTrust.getValue() > 0)
return 1;
else
return Integer.MAX_VALUE;
} catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
Score score = getScore(truster, trust.getTruster());
if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank
// A truster only gives his rank to a trustee if he has assigned a strictly positive trust value
if(trust.getValue() > 0 ) {
// We give the rank to the trustee if it is better than its current rank or he has no rank yet.
if(rank == -1 || score.getRank() < rank)
rank = score.getRank();
} else {
// If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster.
if(rank == -1)
rank = Integer.MAX_VALUE;
}
}
} catch (NotInTrustTreeException e) {}
}
if(rank == -1)
return -1;
else if(rank == Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return rank+1;
}
/**
* Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress.
* This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called.
*
* ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)}
* for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}}
* </code>
*/
protected void beginTrustListImport() {
if(logMINOR) Logger.minor(this, "beginTrustListImport()");
if(mTrustListImportInProgress) {
abortTrustListImport(new RuntimeException("There was already a trust list import in progress!"));
mFullScoreComputationNeeded = true;
computeAllScoresWithoutCommit();
assert(mFullScoreComputationNeeded == false);
}
mTrustListImportInProgress = true;
assert(!mFullScoreComputationNeeded);
assert(computeAllScoresWithoutCommit()); // The database is intact before the import
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file.
* @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file.
*/
protected void abortTrustListImport(Exception e, LogLevel logLevel) {
if(logMINOR) Logger.minor(this, "abortTrustListImport()");
assert(mTrustListImportInProgress);
mTrustListImportInProgress = false;
mFullScoreComputationNeeded = false;
Persistent.checkedRollback(mDB, this, e, logLevel);
assert(computeAllScoresWithoutCommit()); // Test rollback.
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR}
*/
protected void abortTrustListImport(Exception e) {
abortTrustListImport(e, Logger.LogLevel.ERROR);
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Finishes the import of the current trust list and performs score computation.
*
* ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it!
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*/
protected void finishTrustListImport() {
if(logMINOR) Logger.minor(this, "finishTrustListImport()");
if(!mTrustListImportInProgress) {
Logger.error(this, "There was no trust list import in progress!");
return;
}
if(mFullScoreComputationNeeded) {
computeAllScoresWithoutCommit();
assert(!mFullScoreComputationNeeded); // It properly clears the flag
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable
}
else
assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked.
mTrustListImportInProgress = false;
}
/**
* Updates all trust trees which are affected by the given modified score.
* For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()}
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; }
* }}}
*/
private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) {
if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
// We only include the time measurement if we actually do something.
// If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included.
boolean includeMeasurement = false;
final boolean trustWasCreated = (oldTrust == null);
final boolean trustWasDeleted = (newTrust == null);
final boolean trustWasModified = !trustWasCreated && !trustWasDeleted;
if(trustWasCreated && trustWasDeleted)
throw new NullPointerException("No old/new trust specified.");
if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster())
throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee())
throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
// We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values
// which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best
// rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity
// then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because
// the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank.
if(trustWasDeleted) {
mFullScoreComputationNeeded = true;
}
if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) {
includeMeasurement = true;
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
try {
// Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score.
if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0)
continue;
} catch(NotInTrustTreeException e) {
continue;
}
// See explanation above "We cannot iteratively REMOVE an inherited rank..."
if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) {
mFullScoreComputationNeeded = true;
break;
}
final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>();
unprocessedEdges.add(newTrust);
while(!unprocessedEdges.isEmpty()) {
final Trust trust = unprocessedEdges.removeFirst();
final Identity trustee = trust.getTrustee();
if(trustee == treeOwner)
continue;
Score currentStoredTrusteeScore;
boolean scoreExistedBefore;
try {
currentStoredTrusteeScore = getScore(treeOwner, trustee);
scoreExistedBefore = true;
} catch(NotInTrustTreeException e) {
scoreExistedBefore = false;
currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0);
}
final Score oldScore = currentStoredTrusteeScore.clone();
boolean oldShouldFetch = shouldFetchIdentity(trustee);
final int newScoreValue = computeScoreValue(treeOwner, trustee);
final int newRank = computeRank(treeOwner, trustee);
final int newCapacity = computeCapacity(treeOwner, trustee, newRank);
final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity);
// Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value,
// the rank and capacity are always computed based on the trust value of the own identity so we must also check this here:
if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank
&& (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore
mFullScoreComputationNeeded = true;
break;
}
if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) {
mFullScoreComputationNeeded = true;
break;
}
// We are OK to update it now. We must not update the values of the stored score object before determining whether we need
// a full score computation - the full computation needs the old values of the object.
currentStoredTrusteeScore.setValue(newScore.getScore());
currentStoredTrusteeScore.setRank(newScore.getRank());
currentStoredTrusteeScore.setCapacity(newScore.getCapacity());
// Identities should not get into the queue if they have no rank, see the large if() about 20 lines below
assert(currentStoredTrusteeScore.getRank() >= 0);
if(currentStoredTrusteeScore.getRank() >= 0) {
currentStoredTrusteeScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore);
}
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee);
trustee.markForRefetch();
trustee.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee);
mFetcher.storeStartFetchCommandWithoutCommit(trustee);
}
else if(oldShouldFetch && !shouldFetchIdentity(trustee)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee);
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
// If the rank or capacity changed then the trustees might be affected because the could have inherited theirs
if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) {
// If this identity has no capacity or no rank then it cannot affect its trustees:
// (- If it had none and it has none now then there is none which can be inherited, this is obvious)
// - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed
if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) {
// We need to update the trustees of trustee
for(Trust givenTrust : getGivenTrusts(trustee)) {
unprocessedEdges.add(givenTrust);
}
}
}
}
if(mFullScoreComputationNeeded)
break;
}
}
if(includeMeasurement) {
++mIncrementalScoreRecomputationCount;
mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
}
if(logMINOR) {
final String time = includeMeasurement ?
("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s")
: ("Time not measured: Computation was aborted before doing anything.");
if(!mFullScoreComputationNeeded)
Logger.minor(this, "Incremental computation of all Scores finished. " + time);
else
Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time);
}
if(!mTrustListImportInProgress) {
if(mFullScoreComputationNeeded) {
// TODO: Optimization: This uses very much CPU and memory. Write a partial computation function...
// TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT
// keep all objects in memory etc.
computeAllScoresWithoutCommit();
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable
} else {
assert(computeAllScoresWithoutCommit()); // This function worked correctly.
}
} else { // a trust list import is in progress
// We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore
// updateScoresWithoutCommit is called often during import of a single trust list
// assert(computeAllScoresWithoutCommit());
}
}
/* Client interface functions */
public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException {
try {
getIdentityByURI(requestURI);
throw new InvalidParameterException("We already have this identity");
}
catch(UnknownIdentityException e) {
final Identity identity = new Identity(this, requestURI, null, false);
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e2) {
Persistent.checkedRollbackAndThrow(mDB, this, e2);
}
}
// The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher.
// TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust.
Logger.normal(this, "addIdentity(): " + identity);
return identity;
}
}
public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context)
throws MalformedURLException, InvalidParameterException {
FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME);
return createOwnIdentity(keypair[0], nickName, publishTrustList, context);
}
/**
* @param context A context with which you want to use the identity. Null if you want to add it later.
*/
public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName,
boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException {
synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit()
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
OwnIdentity identity;
try {
identity = getOwnIdentityByURI(insertURI);
throw new InvalidParameterException("The URI you specified is already used by the own identity " +
identity.getNickname() + ".");
}
catch(UnknownIdentityException uie) {
identity = new OwnIdentity(this, insertURI, nickName, publishTrustList);
if(context != null)
identity.addContext(context);
if(publishTrustList) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
}
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
initTrustTreeWithoutCommit(identity);
beginTrustListImport();
// Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation.
mFullScoreComputationNeeded = true;
for(String seedURI : SEED_IDENTITIES) {
try {
setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity.");
} catch(UnknownIdentityException e) {
Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e);
}
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
if(mIntroductionClient != null)
mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles.
if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")");
return identity;
}
catch(RuntimeException e) {
abortTrustListImport(e); // Rolls back for us
throw e; // Satisfy the compiler
}
}
}
}
}
}
/**
* This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}.
*
* The {@link OwnIdentity} is not deleted because this would be a security issue:
* If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target
*
* @param id The {@link Identity.IdentityID} of the identity.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID.
*/
public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException {
Logger.normal(this, "deleteOwnIdentity(): Starting... ");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
final OwnIdentity oldIdentity = getOwnIdentityByID(id);
try {
Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity);
// We don't need any score computations to happen (explanation will follow below) so we don't need the following:
/* beginTrustListImport(); */
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
final Identity newIdentity;
try {
newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
} catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
} catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
}
newIdentity.setContexts(oldIdentity.getContexts());
newIdentity.setProperties(oldIdentity.getProperties());
try {
newIdentity.setEdition(oldIdentity.getEdition());
} catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen
throw new RuntimeException(e);
}
// In theory we do not need to re-fetch the current trust list edition:
// The trust list of an own identity is always stored completely in the database, i.e. all trustees exist.
// HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that
// the current edition of the old OwndIdentity was not fetched yet.
// So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well.
if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) {
newIdentity.onFetched(oldIdentity.getLastFetchedDate());
}
// An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already.
newIdentity.storeWithoutCommit();
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust;
try {
newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
}
assert(getScores(oldIdentity).size() == 0);
// Delete all given scores:
// Non-own identities do not assign scores to other identities so we can just delete them.
for(Score oldScore : getGivenScores(oldIdentity)) {
final Identity trustee = oldScore.getTrustee();
final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee);
oldScore.deleteWithoutCommit();
// If the OwnIdentity which we are converting was the only source of trust to the trustee
// of this Score value, the should-fetch state of the trustee might change to false.
if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) {
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
}
assert(getGivenScores(oldIdentity).size() == 0);
// Copy all given trusts:
// We don't have to use the removeTrust/setTrust functions because the score graph does not need updating:
// - To the rating of the converted identity in the score graphs of other own identities it is irrelevant
// whether it is an own identity or not. The rating should never depend on whether it is an own identity!
// - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted
// completely and therefore it does not need to be updated.
for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) {
Trust newGivenTrust;
try {
newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(),
oldGivenTrust.getValue(), oldGivenTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newGivenTrust.equals(oldGivenTrust)); */
oldGivenTrust.deleteWithoutCommit();
newGivenTrust.storeWithoutCommit();
}
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(newIdentity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity);
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
Logger.normal(this, "deleteOwnIdentity(): Finished.");
}
/**
* NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()}
*/
public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException {
Logger.normal(this, "restoreOwnIdentity(): Starting... ");
OwnIdentity identity;
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
long edition = 0;
try {
edition = Math.max(edition, insertFreenetURI.getEdition());
} catch(IllegalStateException e) {
// The user supplied URI did not have an edition specified
}
try { // Try replacing an existing non-own version of the identity with an OwnIdentity
Identity oldIdentity = getIdentityByURI(insertFreenetURI);
if(oldIdentity instanceof OwnIdentity)
throw new InvalidParameterException("There is already an own identity with the given URI pair.");
Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity);
// Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function.
// But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference
// implementation will fail if two identities with the same ID exist.
// This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph
// but we must also store the own version to be able to modify the trust graph.
beginTrustListImport();
// We already have fetched this identity as a stranger's one. We need to update the database.
identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
/* We re-fetch the most recent edition to make sure all trustees are imported */
edition = Math.max(edition, oldIdentity.getEdition());
identity.restoreEdition(edition, oldIdentity.getLastFetchedDate());
identity.setContexts(oldIdentity.getContexts());
identity.setProperties(oldIdentity.getProperties());
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
// Nothing has changed about the actual score so we do not notify.
// mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore);
}
assert(getScores(oldIdentity).size() == 0);
// What we do NOT have to deal with is the given scores of the old identity:
// Given scores do NOT exist for non-own identities, so there are no old ones to update.
// Of cause there WILL be scores because it is an own identity now.
// They will be created automatically when updating the given trusts
// - so thats what we will do now.
// Update all given trusts
for(Trust givenTrust : getGivenTrusts(oldIdentity)) {
// TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could:
// - manually delete the old Trust objects from the database
// - manually store the new trust objects
// - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version
// of setTrustWithoutCommit which deals with that.
// But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit:
// To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make
// it only update the parts of the trust graph which are affected.
// Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests.
removeTrustWithoutCommit(givenTrust);
setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment());
}
// We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit
// which would re-create scores of the old identity. We later call it AFTER deleting the old identity.
/* finishTrustListImport(); */
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
finishTrustListImport();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
} catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it.
identity = new OwnIdentity(this, insertFreenetURI, null, false);
Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity);
identity.restoreEdition(edition, null);
// Store the new identity
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
}
mFetcher.storeStartFetchCommandWithoutCommit(identity);
// This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function
abortTrustListImport(e); // Does rollback for us
throw e;
} else {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
}
Logger.normal(this, "restoreOwnIdentity(): Finished.");
}
public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment)
throws UnknownIdentityException, NumberFormatException, InvalidParameterException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
Identity trustee = getIdentityByID(trusteeID);
setTrust(truster, trustee, value, comment);
}
public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
final Identity trustee = getIdentityByID(trusteeID);
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
removeTrustWithoutCommit(truster, trustee);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Enables or disables the publishing of the trust list of an {@link OwnIdentity}.
* The trust list contains all trust values which the OwnIdentity has assigned to other identities.
*
* @see OwnIdentity#setPublishTrustList(boolean)
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishTrustList Whether to publish the trust list.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}.
*/
public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setPublishTrustList(publishTrustList);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity);
}
/**
* Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}.
*
* If publishIntroductionPuzzles==true adds, if false removes:
* - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT}
* - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT}
*
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishIntroductionPuzzles Whether to publish introduction puzzles.
* @throws UnknownIdentityException If there is no identity with the given ownIdentityID
* @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list.
*/
public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
if(!identity.doesPublishTrustList())
throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!");
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
if(publishIntroductionPuzzles) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
} else {
identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY);
}
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity);
}
public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.addContext(newContext);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeContext(context);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'");
}
public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException {
return getIdentityByID(identityID).getProperty(property);
}
public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setProperty(property, value);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeProperty(property);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'");
}
public String getVersion() {
return Version.getMarketingVersion();
}
public long getRealVersion() {
return Version.getRealVersion();
}
public String getString(String key) {
return getBaseL10n().getString(key);
}
public void setLanguage(LANGUAGE newLanguage) {
WebOfTrust.l10n = new PluginL10n(this, newLanguage);
if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode);
}
public PluginRespirator getPluginRespirator() {
return mPR;
}
public ExtObjectContainer getDatabase() {
return mDB;
}
public Configuration getConfig() {
return mConfig;
}
public SubscriptionManager getSubscriptionManager() {
return mSubscriptionManager;
}
public IdentityFetcher getIdentityFetcher() {
return mFetcher;
}
public XMLTransformer getXMLTransformer() {
return mXMLTransformer;
}
public IntroductionPuzzleStore getIntroductionPuzzleStore() {
return mPuzzleStore;
}
public IntroductionClient getIntroductionClient() {
return mIntroductionClient;
}
protected FCPInterface getFCPInterface() {
return mFCPInterface;
}
public RequestClient getRequestClient() {
return mRequestClient;
}
/**
* This is where our L10n files are stored.
* @return Path of our L10n files.
*/
public String getL10nFilesBasePath() {
return "plugins/WebOfTrust/l10n/";
}
/**
* This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ...
* @return Mask of the L10n files.
*/
public String getL10nFilesMask() {
return "lang_${lang}.l10n";
}
/**
* Override L10n files are stored on the disk, their names should be explicit
* we put here the plugin name, and the "override" indication. Plugin L10n
* override is not implemented in the node yet.
* @return Mask of the override L10n files.
*/
public String getL10nOverrideFilesMask() {
return "WebOfTrust_lang_${lang}.override.l10n";
}
/**
* Get the ClassLoader of this plugin. This is necessary when getting
* resources inside the plugin's Jar, for example L10n files.
* @return ClassLoader object
*/
public ClassLoader getPluginClassLoader() {
return WebOfTrust.class.getClassLoader();
}
/**
* Access to the current L10n data.
*
* @return L10n object.
*/
public BaseL10n getBaseL10n() {
return WebOfTrust.l10n.getBase();
}
public int getNumberOfFullScoreRecomputations() {
return mFullScoreRecomputationCount;
}
public synchronized double getAverageFullScoreRecomputationTime() {
return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000);
}
public int getNumberOfIncrementalScoreRecomputations() {
return mIncrementalScoreRecomputationCount;
}
public synchronized double getAverageIncrementalScoreRecomputationTime() {
return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000);
}
/**
* Tests whether two WoT are equal.
* This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests.
*/
public synchronized boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof WebOfTrust))
return false;
WebOfTrust other = (WebOfTrust)obj;
synchronized(other) {
{ // Compare own identities
final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities();
if(allIdentities.size() != other.getAllOwnIdentities().size())
return false;
for(OwnIdentity identity : allIdentities) {
try {
if(!identity.equals(other.getOwnIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare identities
final ObjectSet<Identity> allIdentities = getAllIdentities();
if(allIdentities.size() != other.getAllIdentities().size())
return false;
for(Identity identity : allIdentities) {
try {
if(!identity.equals(other.getIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare trusts
final ObjectSet<Trust> allTrusts = getAllTrusts();
if(allTrusts.size() != other.getAllTrusts().size())
return false;
for(Trust trust : allTrusts) {
try {
Identity otherTruster = other.getIdentityByID(trust.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID());
if(!trust.equals(other.getTrust(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotTrustedException e) {
return false;
}
}
}
{ // Compare scores
final ObjectSet<Score> allScores = getAllScores();
if(allScores.size() != other.getAllScores().size())
return false;
for(Score score : allScores) {
try {
OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID());
if(!score.equals(other.getScore(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotInTrustTreeException e) {
return false;
}
}
}
}
return true;
}
}
| private synchronized void deleteDuplicateObjects() {
synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity)
synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity)
synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity)
synchronized(Persistent.transactionLock(mDB)) {
try {
HashSet<String> deleted = new HashSet<String>();
if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ...");
for(Identity identity : getAllIdentities()) {
Query q = mDB.query();
q.constrain(Identity.class);
q.descend("mID").constrain(identity.getID());
q.constrain(identity).identity().not();
ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q);
for(Identity duplicate : duplicates) {
if(deleted.contains(duplicate.getID()) == false) {
Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI());
deleteWithoutCommit(duplicate);
Persistent.checkedCommit(mDB, this);
}
}
deleted.add(identity.getID());
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
} // synchronized(mPuzzleStore) {
// synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ...");
boolean duplicateTrustFound = false;
for(OwnIdentity truster : getAllOwnIdentities()) {
HashSet<String> givenTo = new HashSet<String>();
for(Trust trust : getGivenTrusts(truster)) {
if(givenTo.contains(trust.getTrustee().getID()) == false)
givenTo.add(trust.getTrustee().getID());
else {
Logger.error(this, "Deleting duplicate given trust:" + trust);
removeTrustWithoutCommit(trust);
duplicateTrustFound = true;
}
}
}
if(duplicateTrustFound) {
computeAllScoresWithoutCommit();
}
Persistent.checkedCommit(mDB, this);
if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects.");
}
catch(RuntimeException e) {
Persistent.checkedRollback(mDB, this, e);
}
} // synchronized(Persistent.transactionLock(mDB)) {
} // synchronized(mSubscriptionManager) {
} // synchronized(mFetcher) {
/* TODO: Also delete duplicate score */
}
/**
* Debug function for deleting trusts or scores of which one of the involved partners is missing.
*/
private synchronized void deleteOrphanObjects() {
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanTrustFound = false;
Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q);
for(Trust trust : orphanTrusts) {
if(trust.getTruster() != null && trust.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust);
continue;
}
Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee());
orphanTrustFound = true;
trust.deleteWithoutCommit();
// No need to update subscriptions as the trust is broken anyway.
}
if(orphanTrustFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
// synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already.
synchronized(mFetcher) { // For computeAllScoresWithoutCommit()
synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit()
synchronized(Persistent.transactionLock(mDB)) {
try {
boolean orphanScoresFound = false;
Query q = mDB.query();
q.constrain(Score.class);
q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity());
ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q);
for(Score score : orphanScores) {
if(score.getTruster() != null && score.getTrustee() != null) {
// TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore.
Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score);
continue;
}
Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee());
orphanScoresFound = true;
score.deleteWithoutCommit();
// No need to update subscriptions as the score is broken anyway.
}
if(orphanScoresFound) {
computeAllScoresWithoutCommit();
Persistent.checkedCommit(mDB, this);
}
}
catch(Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
/**
* Warning: This function is not synchronized, use it only in single threaded mode.
* @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist.
*/
@SuppressWarnings("deprecation")
private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) {
final Query query = database.query();
query.constrain(Configuration.class);
@SuppressWarnings("unchecked")
ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute();
switch(result.size()) {
case 1: {
final Configuration config = (Configuration)result.next();
config.initializeTransient(wot, database);
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
return config.getDatabaseFormatVersion();
}
default:
return -1;
}
}
/**
* Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists.
* @return The config object.
*/
private synchronized Configuration getOrCreateConfig() {
final Query query = mDB.query();
query.constrain(Configuration.class);
final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query);
switch(result.size()) {
case 1: {
final Configuration config = result.next();
// For the HashMaps to stay alive we need to activate to full depth.
config.checkedActivate(4);
config.setDefaultValues(false);
config.storeAndCommit();
return config;
}
case 0: {
final Configuration config = new Configuration(this);
config.initializeTransient(this);
config.storeAndCommit();
return config;
}
default:
throw new RuntimeException("Multiple config objects found: " + result.size());
}
}
/** Capacity is the maximum amount of points an identity can give to an other by trusting it.
*
* Values choice :
* Advogato Trust metric recommends that values decrease by rounded 2.5 times.
* This makes sense, making the need of 3 N+1 ranked people to overpower
* the trust given by a N ranked identity.
*
* Number of ranks choice :
* When someone creates a fresh identity, he gets the seed identity at
* rank 1 and freenet developpers at rank 2. That means that
* he will see people that were :
* - given 7 trust by freenet devs (rank 2)
* - given 17 trust by rank 3
* - given 50 trust by rank 4
* - given 100 trust by rank 5 and above.
* This makes the range small enough to avoid a newbie
* to even see spam, and large enough to make him see a reasonnable part
* of the community right out-of-the-box.
* Of course, as soon as he will start to give trust, he will put more
* people at rank 1 and enlarge his WoT.
*/
protected static final int capacities[] = {
100,// Rank 0 : Own identities
40, // Rank 1 : Identities directly trusted by ownIdenties
16, // Rank 2 : Identities trusted by rank 1 identities
6, // So on...
2,
1 // Every identity above rank 5 can give 1 point
}; // Identities with negative score have zero capacity
/**
* Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much
* trust points an identity can add to the score of identities which it has assigned trust values to.
* The higher the rank of an identity, the less is it's capacity.
*
* If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less
* than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0.
*
* If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value:
* The decision of the truster should always overpower the view of remote identities.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed
* @param trustee The {@link Identity} of which the capacity shall be computed.
* @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust,
* - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view.
*/
private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) {
if(truster == trustee)
return 100;
try {
// FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually
// need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert.
if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit.
assert(rank == Integer.MAX_VALUE);
return 0;
}
} catch(NotTrustedException e) { }
if(rank == -1 || rank == Integer.MAX_VALUE)
return 0;
return (rank < capacities.length) ? capacities[rank] : 1;
}
/**
* Reference-implementation of score computation. This means:<br />
* - It is not used by the real WoT code because its slow<br />
* - It is used by unit tests (and WoT) to check whether the real implementation works<br />
* - It is the function which you should read if you want to understand how WoT works.<br />
*
* Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br />
*
* There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br />
*
* Further, rank values are shortest paths and the path-finding algorithm is not executed from the source
* to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path.
* Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database
* and affect many others. So it is useful to have this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}}
* </code>
*
* @return True if all stored scores were correct. False if there were any errors in stored scores.
*/
protected boolean computeAllScoresWithoutCommit() {
if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
boolean returnValue = true;
final ObjectSet<Identity> allIdentities = getAllIdentities();
// Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity.
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
// At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner.
// An identity is visible if there is a trust chain from the owner to it.
// The rank is the distance in trust steps from the treeOwner.
// So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on.
final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2);
// Compute the rank values
{
// For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters.
// The inner loop then pulls out one unprocessed identity and computes the rank of its trustees:
// All trustees which have received positive (> 0) trust will get his rank + 1
// Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE.
// Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all.
// Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none.
//
// Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value:
// The decision of the own identity shall not be overpowered by the view of the remote identities.
//
// The purpose of differentiation between Integer.MAX_VALUE and -1 is:
// Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing
// them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and
// have a way of telling the user "this identity is not trusted" by keeping a score object of them.
// Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where
// we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank
// - and we never import their trust lists.
// We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved
// introduction puzzles cannot inherit their rank to their trustees.
final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>();
// The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE
try {
Score selfScore = getScore(treeOwner, treeOwner);
if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one
rankValues.put(treeOwner, selfScore.getRank());
unprocessedTrusters.addLast(treeOwner);
} else {
rankValues.put(treeOwner, null);
}
} catch(NotInTrustTreeException e) {
// This only happens in unit tests.
}
while(!unprocessedTrusters.isEmpty()) {
final Identity truster = unprocessedTrusters.removeFirst();
final Integer trusterRank = rankValues.get(truster);
// The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all.
if(trusterRank == null || trusterRank == Integer.MAX_VALUE) {
// (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security)
continue;
}
final int trusteeRank = trusterRank + 1;
for(Trust trust : getGivenTrusts(truster)) {
final Identity trustee = trust.getTrustee();
final Integer oldTrusteeRank = rankValues.get(trustee);
if(oldTrusteeRank == null) { // The trustee was not processed yet
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
else
rankValues.put(trustee, Integer.MAX_VALUE);
} else {
// Breadth first search will process all rank one identities are processed before any rank two identities, etc.
assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank);
if(oldTrusteeRank == Integer.MAX_VALUE) {
// If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not
// given by the tree owner.
try {
final Trust treeOwnerTrust = getTrust(treeOwner, trustee);
assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct?
} catch(NotTrustedException e) {
if(trust.getValue() > 0) {
rankValues.put(trustee, trusteeRank);
unprocessedTrusters.addLast(trustee);
}
}
}
}
}
}
}
// Rank values of all visible identities are computed now.
// Next step is to compute the scores of all identities
for(Identity target : allIdentities) {
// The score of an identity is the sum of all weighted trust values it has received.
// Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank.
Integer targetScore;
final Integer targetRank = rankValues.get(target);
if(targetRank == null) {
targetScore = null;
} else {
// The treeOwner trusts himself.
if(targetRank == 0) {
targetScore = Integer.MAX_VALUE;
}
else {
// If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score.
try {
targetScore = (int)getTrust(treeOwner, target).getValue();
} catch(NotTrustedException e) {
targetScore = 0;
for(Trust receivedTrust : getReceivedTrusts(target)) {
final Identity truster = receivedTrust.getTruster();
final Integer trusterRank = rankValues.get(truster);
// The capacity is a weight function for trust values which are given from an identity:
// The higher the rank, the less the capacity.
// If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0.
final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1);
targetScore += (receivedTrust.getValue() * capacity) / 100;
}
}
}
}
Score newScore = null;
if(targetScore != null) {
newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank));
}
boolean needToCheckFetchStatus = false;
boolean oldShouldFetch = false;
int oldCapacity = 0;
// Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct.
try {
Score currentStoredScore = getScore(treeOwner, target);
oldCapacity = currentStoredScore.getCapacity();
if(newScore == null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
currentStoredScore.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null);
} else {
if(!newScore.equals(currentStoredScore)) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
final Score oldScore = currentStoredScore.clone();
currentStoredScore.setRank(newScore.getRank());
currentStoredScore.setCapacity(newScore.getCapacity());
currentStoredScore.setValue(newScore.getScore());
currentStoredScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore);
}
}
} catch(NotInTrustTreeException e) {
oldCapacity = 0;
if(newScore != null) {
returnValue = false;
if(!mFullScoreComputationNeeded)
Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException());
needToCheckFetchStatus = true;
oldShouldFetch = shouldFetchIdentity(target);
newScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore);
}
}
if(needToCheckFetchStatus) {
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target);
target.markForRefetch();
target.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target);
mFetcher.storeStartFetchCommandWithoutCommit(target);
}
else if(oldShouldFetch && !shouldFetchIdentity(target)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target);
mFetcher.storeAbortFetchCommandWithoutCommit(target);
}
}
}
}
mFullScoreComputationNeeded = false;
++mFullScoreRecomputationCount;
mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
if(logMINOR) {
Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s");
}
return returnValue;
}
private synchronized void createSeedIdentities() {
synchronized(mSubscriptionManager) {
for(String seedURI : SEED_IDENTITIES) {
synchronized(Persistent.transactionLock(mDB)) {
try {
final Identity existingSeed = getIdentityByURI(seedURI);
final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager
if(existingSeed instanceof OwnIdentity) {
final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed;
ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY,
Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT));
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed);
ownExistingSeed.storeAndCommit();
}
else {
try {
existingSeed.setEdition(new FreenetURI(seedURI).getEdition());
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed);
existingSeed.storeAndCommit();
} catch(InvalidParameterException e) {
/* We already have the latest edition stored */
}
}
}
catch (UnknownIdentityException uie) {
try {
final Identity newSeed = new Identity(this, seedURI, null, true);
// We have to explicitly set the edition number because the constructor only considers the given edition as a hint.
newSeed.setEdition(new FreenetURI(seedURI).getEdition());
newSeed.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed);
Persistent.checkedCommit(mDB, this);
} catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
catch (Exception e) {
Persistent.checkedRollback(mDB, this, e);
}
}
}
}
}
public void terminate() {
if(logDEBUG) Logger.debug(this, "WoT plugin terminating ...");
/* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */
try {
if(mWebInterface != null)
this.mWebInterface.unload();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionClient != null)
mIntroductionClient.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mIntroductionServer != null)
mIntroductionServer.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mInserter != null)
mInserter.terminate();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mFetcher != null)
mFetcher.stop();
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mSubscriptionManager != null)
mSubscriptionManager.stop();
} catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
try {
if(mDB != null) {
/* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending.
* If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction.
* - All transactions should be committed after obtaining the lock() on the database. */
synchronized(Persistent.transactionLock(mDB)) {
System.gc();
mDB.rollback();
System.gc();
mDB.close();
}
}
}
catch(Exception e) {
Logger.error(this, "Error during termination.", e);
}
if(logDEBUG) Logger.debug(this, "WoT plugin terminated.");
}
/**
* Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>.
*/
public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
mFCPInterface.handle(replysender, params, data, accesstype);
}
/**
* Loads an own or normal identity from the database, querying on its ID.
*
* @param id The ID of the identity to load
* @return The identity matching the supplied ID.
* @throws DuplicateIdentityException if there are more than one identity with this id in the database
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(Identity.class);
query.descend("mID").constrain(id);
final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Gets an OwnIdentity by its ID.
*
* @param id The unique identifier to query an OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if there is now OwnIdentity with that id
*/
public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException {
final Query query = mDB.query();
query.constrain(OwnIdentity.class);
query.descend("mID").constrain(id);
final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query);
switch(result.size()) {
case 1: return result.next();
case 0: throw new UnknownIdentityException(id);
default: throw new DuplicateIdentityException(id, result.size());
}
}
/**
* Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI})
*
* @param uri The requestURI of the identity
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
*/
public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Loads an identity from the database, querying on its requestURI (as String)
*
* @param uri The requestURI of the identity which will be converted to {@link FreenetURI}
* @return The identity matching the supplied requestURI
* @throws UnknownIdentityException if there is no identity with this id in the database
* @throws MalformedURLException if the requestURI isn't a valid FreenetURI
*/
public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getIdentityByURI(new FreenetURI(uri));
}
/**
* Gets an OwnIdentity by its requestURI (a {@link FreenetURI}).
* The OwnIdentity's unique identifier is extracted from the supplied requestURI.
*
* @param uri The requestURI of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
*/
public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException {
return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString());
}
/**
* Gets an OwnIdentity by its requestURI (as String).
* The given String is converted to {@link FreenetURI} in order to extract a unique id.
*
* @param uri The requestURI (as String) of the desired OwnIdentity
* @return The requested OwnIdentity
* @throws UnknownIdentityException if the OwnIdentity isn't in the database
* @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI
*/
public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException {
return getOwnIdentityByURI(new FreenetURI(uri));
}
/**
* Returns all identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database
*/
public ObjectSet<Identity> getAllIdentities() {
final Query query = mDB.query();
query.constrain(Identity.class);
return new Persistent.InitializingObjectSet<Identity>(this, query);
}
public static enum SortOrder {
ByNicknameAscending,
ByNicknameDescending,
ByScoreAscending,
ByScoreDescending,
ByLocalTrustAscending,
ByLocalTrustDescending
}
/**
* Get a filtered and sorted list of identities.
* You have to synchronize on this WoT when calling the function and processing the returned list.
*/
public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) {
Query q = mDB.query();
switch(sortInstruction) {
case ByNicknameAscending:
q.constrain(Identity.class);
q.descend("mNickname").orderAscending();
break;
case ByNicknameDescending:
q.constrain(Identity.class);
q.descend("mNickname").orderDescending();
break;
case ByScoreAscending:
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByScoreDescending:
// TODO: This excludes identities which have no score
q.constrain(Score.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
case ByLocalTrustAscending:
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderAscending();
q = q.descend("mTrustee");
break;
case ByLocalTrustDescending:
// TODO: This excludes untrusted identities.
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mValue").orderDescending();
q = q.descend("mTrustee");
break;
}
if(nickFilter != null) {
nickFilter = nickFilter.trim();
if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like();
}
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Identity> getAllNonOwnIdentities() {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently
* modified identities will be at the beginning of the list.
*
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* Used by the IntroductionClient for fetching puzzles from recently modified identities.
*/
public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () {
final Query q = mDB.query();
q.constrain(Identity.class);
q.constrain(OwnIdentity.class).not();
/* TODO: As soon as identities announce that they were online every day, uncomment the following line */
/* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */
q.descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Identity>(this, q);
}
/**
* Returns all own identities that are in the database
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all identities present in the database.
*/
public ObjectSet<OwnIdentity> getAllOwnIdentities() {
final Query q = mDB.query();
q.constrain(OwnIdentity.class);
return new Persistent.InitializingObjectSet<OwnIdentity>(this, q);
}
/**
* DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST!
* IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS:
* - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will.
* - Especially it might be an information leak if the trust values of other OwnIdentities are deleted!
* - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption.
*
* The intended purpose of this function is:
* - To specify which objects have to be dealt with when messing with storage of an identity.
* - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them.
* However, the implementations of those functions might cause leaks by forgetting to delete certain object members.
* If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty.
* You then can check whether the database actually IS empty to test for leakage.
*
* You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function.
*/
private void deleteWithoutCommit(Identity identity) {
// We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport.
// If the caller already handles that for us though, we should not call those function again.
// So we check whether the caller already started an import.
boolean trustListImportWasInProgress = mTrustListImportInProgress;
try {
if(!trustListImportWasInProgress)
beginTrustListImport();
if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ...");
if(logDEBUG) Logger.debug(this, "Deleting received scores...");
for(Score score : getScores(identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
if(identity instanceof OwnIdentity) {
if(logDEBUG) Logger.debug(this, "Deleting given scores...");
for(Score score : getGivenScores((OwnIdentity)identity)) {
score.deleteWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null);
}
}
if(logDEBUG) Logger.debug(this, "Deleting received trusts...");
for(Trust trust : getReceivedTrusts(identity)) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
}
if(logDEBUG) Logger.debug(this, "Deleting given trusts...");
for(Trust givenTrust : getGivenTrusts(identity)) {
givenTrust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null);
// We call computeAllScores anyway so we do not use removeTrustWithoutCommit()
}
mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us.
if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ...");
mPuzzleStore.onIdentityDeletion(identity);
if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command...");
if(mFetcher != null) { // Can be null if we use this function in upgradeDB()
mFetcher.storeAbortFetchCommandWithoutCommit(identity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
}
if(logDEBUG) Logger.debug(this, "Deleting the identity...");
identity.deleteWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null);
if(!trustListImportWasInProgress)
finishTrustListImport();
}
catch(RuntimeException e) {
if(!trustListImportWasInProgress)
abortTrustListImport(e);
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
* Gets the score of this identity in a trust tree.
* Each {@link OwnIdentity} has its own trust tree.
*
* @param truster The owner of the trust tree
* @return The {@link Score} of this Identity in the required trust tree
* @throws NotInTrustTreeException if this identity is not in the required trust tree
*/
public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mID").constrain(new ScoreID(truster, trustee).toString());
final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query);
switch(result.size()) {
case 1:
final Score score = result.next();
assert(score.getTruster() == truster);
assert(score.getTrustee() == trustee);
return score;
case 0: throw new NotInTrustTreeException(truster, trustee);
default: throw new DuplicateScoreException(truster, trustee, result.size());
}
}
/**
* Gets a list of all this Identity's Scores.
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
*
* @return An {@link ObjectSet} containing all {@link Score} this Identity has.
*/
public ObjectSet<Score> getScores(final Identity identity) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTrustee").constrain(identity).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Get a list of all scores which the passed own identity has assigned to other identities.
*
* You have to synchronize on this WoT around the call to this function and the processing of the returned list!
* @return An {@link ObjectSet} containing all {@link Score} this Identity has given.
*/
public ObjectSet<Score> getGivenScores(final OwnIdentity truster) {
final Query query = mDB.query();
query.constrain(Score.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets the best score this Identity has in existing trust trees.
*
* @return the best score this Identity has
* @throws NotInTrustTreeException If the identity has no score in any trusttree.
*/
public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException {
int bestScore = Integer.MIN_VALUE;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestScore = Math.max(score.getScore(), bestScore);
return bestScore;
}
/**
* Gets the best capacity this identity has in any trust tree.
* @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0.
*/
public int getBestCapacity(final Identity identity) throws NotInTrustTreeException {
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
throw new NotInTrustTreeException(identity);
// TODO: Cache the best score of an identity as a member variable.
for(final Score score : scores)
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
return bestCapacity;
}
/**
* Get all scores in the database.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
public ObjectSet<Score> getAllScores() {
final Query query = mDB.query();
query.constrain(Score.class);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Checks whether the given identity should be downloaded.
* @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity.
*/
public boolean shouldFetchIdentity(final Identity identity) {
if(identity instanceof OwnIdentity)
return true;
int bestScore = Integer.MIN_VALUE;
int bestCapacity = 0;
final ObjectSet<Score> scores = getScores(identity);
if(scores.size() == 0)
return false;
// TODO: Cache the best score of an identity as a member variable.
for(Score score : scores) {
bestCapacity = Math.max(score.getCapacity(), bestCapacity);
bestScore = Math.max(score.getScore(), bestScore);
if(bestCapacity > 0 || bestScore >= 0)
return true;
}
return false;
}
/**
* Gets non-own Identities matching a specified score criteria.
* TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The owner of the trust tree, null if you want the trusted identities of all owners.
* @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0
* and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0.
* @return an {@link ObjectSet} containing Scores of the identities that match the criteria
*/
public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) {
final Query query = mDB.query();
query.constrain(Score.class);
if(truster != null)
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").constrain(OwnIdentity.class).not();
/* We include 0 in the list of identities with positive score because solving captchas gives no points to score */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0)
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Score>(this, query);
}
/**
* Gets {@link Trust} from a specified truster to a specified trustee.
*
* @param truster The identity that gives trust to this Identity
* @param trustee The identity which receives the trust
* @return The trust given to the trustee by the specified truster
* @throws NotTrustedException if the truster doesn't trust the trustee
*/
public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mID").constrain(new TrustID(truster, trustee).toString());
final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query);
switch(result.size()) {
case 1:
final Trust trust = result.next();
assert(trust.getTruster() == truster);
assert(trust.getTrustee() == trustee);
return trust;
case 0: throw new NotTrustedException(truster, trustee);
default: throw new DuplicateTrustException(truster, trustee, result.size());
}
}
/**
* Gets all trusts given by the given truster.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster.
* The result is sorted descending by the time we last fetched the trusted identity.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given.
*/
public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
query.descend("mTrustee").descend("mLastFetchedDate").orderDescending();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets given trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param truster The identity which given the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTruster").constrain(truster).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts given by the given truster in a trust list with a different edition than the passed in one.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*/
protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) {
final Query q = mDB.query();
q.constrain(Trust.class);
q.descend("mTruster").constrain(truster).identity();
q.descend("mTrusterTrustListEdition").constrain(edition).not();
return new Persistent.InitializingObjectSet<Trust>(this, q);
}
/**
* Gets all trusts received by the given trustee.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets received trust values of an identity matching a specified trust value criteria.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @param trustee The identity which has received the trust values.
* @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0.
* Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0.
* @return an {@link ObjectSet} containing received trust values that match the criteria.
*/
public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) {
final Query query = mDB.query();
query.constrain(Trust.class);
query.descend("mTrustee").constrain(trustee).identity();
/* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */
if(select > 0)
query.descend("mValue").constrain(0).smaller().not();
else if(select < 0 )
query.descend("mValue").constrain(0).smaller();
else
query.descend("mValue").constrain(0);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gets all trusts.
* You have to synchronize on this WoT when calling the function and processing the returned list!
*
* @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received.
*/
public ObjectSet<Trust> getAllTrusts() {
final Query query = mDB.query();
query.constrain(Trust.class);
return new Persistent.InitializingObjectSet<Trust>(this, query);
}
/**
* Gives some {@link Trust} to another Identity.
* It creates or updates an existing Trust object and make the trustee compute its {@link Score}.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster The Identity that gives the trust
* @param trustee The Identity that receives the trust
* @param newValue Numeric value of the trust
* @param newComment A comment to explain the given value
* @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values.
*/
protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
try { // Check if we are updating an existing trust value
final Trust trust = getTrust(truster, trustee);
final Trust oldTrust = trust.clone();
trust.trusterEditionUpdated();
trust.setComment(newComment);
trust.storeWithoutCommit();
if(trust.getValue() != newValue) {
trust.setValue(newValue);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust);
if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(oldTrust, trust);
}
} catch (NotTrustedException e) {
final Trust trust = new Trust(this, truster, trustee, newValue, newComment);
trust.storeWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust);
if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score.");
updateScoresWithoutCommit(null, trust);
}
truster.updated();
truster.storeWithoutCommit();
// TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't.
// As soon as we have notification-coalescing we might do it.
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster);
}
/**
* Only for being used by WoT internally and by unit tests!
*
* You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function.
*/
void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment)
throws InvalidParameterException {
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
setTrustWithoutCommit(truster, trustee, newValue, newComment);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Deletes a trust object.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
* @param truster
* @param trustee
*/
protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) {
try {
try {
removeTrustWithoutCommit(getTrust(truster, trustee));
} catch (NotTrustedException e) {
Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname());
}
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
/**
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }}}
*
*/
protected void removeTrustWithoutCommit(Trust trust) {
trust.deleteWithoutCommit();
mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null);
updateScoresWithoutCommit(trust, null);
}
/**
* Initializes this OwnIdentity's trust tree without commiting the transaction.
* Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities.
*
* The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE.
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); }
* }
*
* @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen)
*/
private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException {
try {
getScore(identity, identity);
Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity);
return;
} catch (NotInTrustTreeException e) {
final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100);
score.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score);
}
}
/**
* Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified
* trust tree.
*
* @param truster The OwnIdentity that owns the trust tree
* @param trustee The identity for which the score shall be computed.
* @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster.
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return Integer.MAX_VALUE;
int value = 0;
try {
return getTrust(truster, trustee).getValue();
}
catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
final Score trusterScore = getScore(truster, trust.getTruster());
value += ( trust.getValue() * trusterScore.getCapacity() ) / 100;
} catch (NotInTrustTreeException e) {}
}
return value;
}
/**
* Computes the trustees's rank in the trust tree of the truster.
* It gets its best ranked non-zero-capacity truster's rank, plus one.
* If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite).
* If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1.
*
* If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the
* tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision).
*
* The purpose of differentiation between Integer.MAX_VALUE and -1 is:
* Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them
* in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the
* user "this identity is not trusted" by keeping a score object of them.
* Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we
* hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and
* we never download their trust lists.
*
* Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity.
*
* @param truster The OwnIdentity that owns the trust tree
* @return The new Rank if this Identity
* @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen)
*/
private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException {
if(trustee == truster)
return 0;
int rank = -1;
try {
Trust treeOwnerTrust = getTrust(truster, trustee);
if(treeOwnerTrust.getValue() > 0)
return 1;
else
return Integer.MAX_VALUE;
} catch(NotTrustedException e) { }
for(Trust trust : getReceivedTrusts(trustee)) {
try {
Score score = getScore(truster, trust.getTruster());
if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank
// A truster only gives his rank to a trustee if he has assigned a strictly positive trust value
if(trust.getValue() > 0 ) {
// We give the rank to the trustee if it is better than its current rank or he has no rank yet.
if(rank == -1 || score.getRank() < rank)
rank = score.getRank();
} else {
// If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster.
if(rank == -1)
rank = Integer.MAX_VALUE;
}
}
} catch (NotInTrustTreeException e) {}
}
if(rank == -1)
return -1;
else if(rank == Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return rank+1;
}
/**
* Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress.
* This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called.
*
* ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)}
* for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}}
* </code>
*/
protected void beginTrustListImport() {
if(logMINOR) Logger.minor(this, "beginTrustListImport()");
if(mTrustListImportInProgress) {
abortTrustListImport(new RuntimeException("There was already a trust list import in progress!"));
mFullScoreComputationNeeded = true;
computeAllScoresWithoutCommit();
assert(mFullScoreComputationNeeded == false);
}
mTrustListImportInProgress = true;
assert(!mFullScoreComputationNeeded);
assert(computeAllScoresWithoutCommit()); // The database is intact before the import
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(mSubscriptionManager) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already }
* }}}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file.
* @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file.
*/
protected void abortTrustListImport(Exception e, LogLevel logLevel) {
if(logMINOR) Logger.minor(this, "abortTrustListImport()");
assert(mTrustListImportInProgress);
mTrustListImportInProgress = false;
mFullScoreComputationNeeded = false;
Persistent.checkedRollback(mDB, this, e, logLevel);
assert(computeAllScoresWithoutCommit()); // Test rollback.
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Aborts the import of a trust list import and undoes all changes by it.
*
* ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction.
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*
* @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR}
*/
protected void abortTrustListImport(Exception e) {
abortTrustListImport(e, Logger.LogLevel.ERROR);
}
/**
* See {@link beginTrustListImport} for an explanation of the purpose of this function.
* Finishes the import of the current trust list and performs score computation.
*
* ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it!
* ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function.
*
* Synchronization:
* This function does neither lock the database nor commit the transaction. You have to surround it with:
* <code>
* synchronized(WebOfTrust.this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already }
* }}}
* </code>
*/
protected void finishTrustListImport() {
if(logMINOR) Logger.minor(this, "finishTrustListImport()");
if(!mTrustListImportInProgress) {
Logger.error(this, "There was no trust list import in progress!");
return;
}
if(mFullScoreComputationNeeded) {
computeAllScoresWithoutCommit();
assert(!mFullScoreComputationNeeded); // It properly clears the flag
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable
}
else
assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked.
mTrustListImportInProgress = false;
}
/**
* Updates all trust trees which are affected by the given modified score.
* For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()}
*
* This function does neither lock the database nor commit the transaction. You have to surround it with
* synchronized(this) {
* synchronized(mFetcher) {
* synchronized(Persistent.transactionLock(mDB)) {
* try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); }
* catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; }
* }}}
*/
private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) {
if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores...");
final long beginTime = CurrentTimeUTC.getInMillis();
// We only include the time measurement if we actually do something.
// If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included.
boolean includeMeasurement = false;
final boolean trustWasCreated = (oldTrust == null);
final boolean trustWasDeleted = (newTrust == null);
final boolean trustWasModified = !trustWasCreated && !trustWasDeleted;
if(trustWasCreated && trustWasDeleted)
throw new NullPointerException("No old/new trust specified.");
if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster())
throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee())
throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust);
// We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values
// which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best
// rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity
// then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because
// the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank.
if(trustWasDeleted) {
mFullScoreComputationNeeded = true;
}
if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) {
includeMeasurement = true;
for(OwnIdentity treeOwner : getAllOwnIdentities()) {
try {
// Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score.
if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0)
continue;
} catch(NotInTrustTreeException e) {
continue;
}
// See explanation above "We cannot iteratively REMOVE an inherited rank..."
if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) {
mFullScoreComputationNeeded = true;
break;
}
final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>();
unprocessedEdges.add(newTrust);
while(!unprocessedEdges.isEmpty()) {
final Trust trust = unprocessedEdges.removeFirst();
final Identity trustee = trust.getTrustee();
if(trustee == treeOwner)
continue;
Score currentStoredTrusteeScore;
boolean scoreExistedBefore;
try {
currentStoredTrusteeScore = getScore(treeOwner, trustee);
scoreExistedBefore = true;
} catch(NotInTrustTreeException e) {
scoreExistedBefore = false;
currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0);
}
final Score oldScore = currentStoredTrusteeScore.clone();
boolean oldShouldFetch = shouldFetchIdentity(trustee);
final int newScoreValue = computeScoreValue(treeOwner, trustee);
final int newRank = computeRank(treeOwner, trustee);
final int newCapacity = computeCapacity(treeOwner, trustee, newRank);
final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity);
// Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value,
// the rank and capacity are always computed based on the trust value of the own identity so we must also check this here:
if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank
&& (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore
mFullScoreComputationNeeded = true;
break;
}
if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) {
mFullScoreComputationNeeded = true;
break;
}
// We are OK to update it now. We must not update the values of the stored score object before determining whether we need
// a full score computation - the full computation needs the old values of the object.
currentStoredTrusteeScore.setValue(newScore.getScore());
currentStoredTrusteeScore.setRank(newScore.getRank());
currentStoredTrusteeScore.setCapacity(newScore.getCapacity());
// Identities should not get into the queue if they have no rank, see the large if() about 20 lines below
assert(currentStoredTrusteeScore.getRank() >= 0);
if(currentStoredTrusteeScore.getRank() >= 0) {
currentStoredTrusteeScore.storeWithoutCommit();
mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore);
}
// If fetch status changed from false to true, we need to start fetching it
// If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot
// cause new identities to be imported from their trust list, capacity > 0 allows this.
// If the fetch status changed from true to false, we need to stop fetching it
if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) {
if(!oldShouldFetch)
if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee);
else
if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee);
trustee.markForRefetch();
trustee.storeWithoutCommit();
// We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score
// mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee);
mFetcher.storeStartFetchCommandWithoutCommit(trustee);
}
else if(oldShouldFetch && !shouldFetchIdentity(trustee)) {
if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee);
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
// If the rank or capacity changed then the trustees might be affected because the could have inherited theirs
if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) {
// If this identity has no capacity or no rank then it cannot affect its trustees:
// (- If it had none and it has none now then there is none which can be inherited, this is obvious)
// - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed
if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) {
// We need to update the trustees of trustee
for(Trust givenTrust : getGivenTrusts(trustee)) {
unprocessedEdges.add(givenTrust);
}
}
}
}
if(mFullScoreComputationNeeded)
break;
}
}
if(includeMeasurement) {
++mIncrementalScoreRecomputationCount;
mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime;
}
if(logMINOR) {
final String time = includeMeasurement ?
("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s")
: ("Time not measured: Computation was aborted before doing anything.");
if(!mFullScoreComputationNeeded)
Logger.minor(this, "Incremental computation of all Scores finished. " + time);
else
Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time);
}
if(!mTrustListImportInProgress) {
if(mFullScoreComputationNeeded) {
// TODO: Optimization: This uses very much CPU and memory. Write a partial computation function...
// TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT
// keep all objects in memory etc.
computeAllScoresWithoutCommit();
assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable
} else {
assert(computeAllScoresWithoutCommit()); // This function worked correctly.
}
} else { // a trust list import is in progress
// We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore
// updateScoresWithoutCommit is called often during import of a single trust list
// assert(computeAllScoresWithoutCommit());
}
}
/* Client interface functions */
public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException {
try {
getIdentityByURI(requestURI);
throw new InvalidParameterException("We already have this identity");
}
catch(UnknownIdentityException e) {
final Identity identity = new Identity(this, requestURI, null, false);
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
Persistent.checkedCommit(mDB, this);
} catch(RuntimeException e2) {
Persistent.checkedRollbackAndThrow(mDB, this, e2);
}
}
// The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher.
// TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust.
Logger.normal(this, "addIdentity(): " + identity);
return identity;
}
}
public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context)
throws MalformedURLException, InvalidParameterException {
FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME);
return createOwnIdentity(keypair[0], nickName, publishTrustList, context);
}
/**
* @param context A context with which you want to use the identity. Null if you want to add it later.
*/
public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName,
boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException {
synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit()
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
OwnIdentity identity;
try {
identity = getOwnIdentityByURI(insertURI);
throw new InvalidParameterException("The URI you specified is already used by the own identity " +
identity.getNickname() + ".");
}
catch(UnknownIdentityException uie) {
identity = new OwnIdentity(this, insertURI, nickName, publishTrustList);
if(context != null)
identity.addContext(context);
if(publishTrustList) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
}
try {
identity.storeWithoutCommit();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
initTrustTreeWithoutCommit(identity);
beginTrustListImport();
// Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation.
mFullScoreComputationNeeded = true;
for(String seedURI : SEED_IDENTITIES) {
try {
setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity.");
} catch(UnknownIdentityException e) {
Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e);
}
}
finishTrustListImport();
Persistent.checkedCommit(mDB, this);
if(mIntroductionClient != null)
mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles.
if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")");
return identity;
}
catch(RuntimeException e) {
abortTrustListImport(e); // Rolls back for us
throw e; // Satisfy the compiler
}
}
}
}
}
}
/**
* This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}.
*
* The {@link OwnIdentity} is not deleted because this would be a security issue:
* If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target
*
* @param id The {@link Identity.IdentityID} of the identity.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID.
*/
public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException {
Logger.normal(this, "deleteOwnIdentity(): Starting... ");
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
final OwnIdentity oldIdentity = getOwnIdentityByID(id);
try {
Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity);
// We don't need any score computations to happen (explanation will follow below) so we don't need the following:
/* beginTrustListImport(); */
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
final Identity newIdentity;
try {
newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
} catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
} catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen
throw new RuntimeException(e);
}
newIdentity.setContexts(oldIdentity.getContexts());
newIdentity.setProperties(oldIdentity.getProperties());
try {
newIdentity.setEdition(oldIdentity.getEdition());
} catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen
throw new RuntimeException(e);
}
// In theory we do not need to re-fetch the current trust list edition:
// The trust list of an own identity is always stored completely in the database, i.e. all trustees exist.
// HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that
// the current edition of the old OwndIdentity was not fetched yet.
// So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well.
if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) {
newIdentity.onFetched(oldIdentity.getLastFetchedDate());
}
// An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already.
newIdentity.storeWithoutCommit();
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust;
try {
newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
}
assert(getScores(oldIdentity).size() == 0);
// Delete all given scores:
// Non-own identities do not assign scores to other identities so we can just delete them.
for(Score oldScore : getGivenScores(oldIdentity)) {
final Identity trustee = oldScore.getTrustee();
final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee);
oldScore.deleteWithoutCommit();
// If the OwnIdentity which we are converting was the only source of trust to the trustee
// of this Score value, the should-fetch state of the trustee might change to false.
if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) {
mFetcher.storeAbortFetchCommandWithoutCommit(trustee);
}
}
assert(getGivenScores(oldIdentity).size() == 0);
// Copy all given trusts:
// We don't have to use the removeTrust/setTrust functions because the score graph does not need updating:
// - To the rating of the converted identity in the score graphs of other own identities it is irrelevant
// whether it is an own identity or not. The rating should never depend on whether it is an own identity!
// - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted
// completely and therefore it does not need to be updated.
for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) {
Trust newGivenTrust;
try {
newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(),
oldGivenTrust.getValue(), oldGivenTrust.getComment());
} catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen
throw new RuntimeException(e);
}
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newGivenTrust.equals(oldGivenTrust)); */
oldGivenTrust.deleteWithoutCommit();
newGivenTrust.storeWithoutCommit();
}
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
mFetcher.storeStartFetchCommandWithoutCommit(newIdentity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity);
// This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
Logger.normal(this, "deleteOwnIdentity(): Finished.");
}
/**
* NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()}
*/
public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException {
Logger.normal(this, "restoreOwnIdentity(): Starting... ");
OwnIdentity identity;
synchronized(mPuzzleStore) {
synchronized(mFetcher) {
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
long edition = 0;
try {
edition = Math.max(edition, insertFreenetURI.getEdition());
} catch(IllegalStateException e) {
// The user supplied URI did not have an edition specified
}
try { // Try replacing an existing non-own version of the identity with an OwnIdentity
Identity oldIdentity = getIdentityByURI(insertFreenetURI);
if(oldIdentity instanceof OwnIdentity)
throw new InvalidParameterException("There is already an own identity with the given URI pair.");
Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity);
// Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function.
// But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference
// implementation will fail if two identities with the same ID exist.
// This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph
// but we must also store the own version to be able to modify the trust graph.
beginTrustListImport();
// We already have fetched this identity as a stranger's one. We need to update the database.
identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList());
/* We re-fetch the most recent edition to make sure all trustees are imported */
edition = Math.max(edition, oldIdentity.getEdition());
identity.restoreEdition(edition, oldIdentity.getLastFetchedDate());
identity.setContexts(oldIdentity.getContexts());
identity.setProperties(oldIdentity.getProperties());
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
// Copy all received trusts.
// We don't have to modify them because they are user-assigned values and the assignment
// of the user does not change just because the type of the identity changes.
for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) {
Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity,
oldReceivedTrust.getValue(), oldReceivedTrust.getComment());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newReceivedTrust.equals(oldReceivedTrust)); */
oldReceivedTrust.deleteWithoutCommit();
newReceivedTrust.storeWithoutCommit();
}
assert(getReceivedTrusts(oldIdentity).size() == 0);
// Copy all received scores.
// We don't have to modify them because the rating of the identity from the perspective of a
// different own identity should NOT be dependent upon whether it is an own identity or not.
for(Score oldScore : getScores(oldIdentity)) {
Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(),
oldScore.getRank(), oldScore.getCapacity());
// The following assert() cannot be added because it would always fail:
// It would implicitly trigger oldIdentity.equals(identity) which is not the case:
// Certain member values such as the edition might not be equal.
/* assert(newScore.equals(oldScore)); */
oldScore.deleteWithoutCommit();
newScore.storeWithoutCommit();
// Nothing has changed about the actual score so we do not notify.
// mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore);
}
assert(getScores(oldIdentity).size() == 0);
// What we do NOT have to deal with is the given scores of the old identity:
// Given scores do NOT exist for non-own identities, so there are no old ones to update.
// Of cause there WILL be scores because it is an own identity now.
// They will be created automatically when updating the given trusts
// - so thats what we will do now.
// Update all given trusts
for(Trust givenTrust : getGivenTrusts(oldIdentity)) {
// TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could:
// - manually delete the old Trust objects from the database
// - manually store the new trust objects
// - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version
// of setTrustWithoutCommit which deals with that.
// But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit:
// To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make
// it only update the parts of the trust graph which are affected.
// Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests.
removeTrustWithoutCommit(givenTrust);
setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment());
}
// We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit
// which would re-create scores of the old identity. We later call it AFTER deleting the old identity.
/* finishTrustListImport(); */
mPuzzleStore.onIdentityDeletion(oldIdentity);
mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity);
// NOTICE:
// If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing
// now to prevent leakage of the identity object.
// But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only.
// Therefore, it is OK that the fetcher does not immediately process the commands now.
oldIdentity.deleteWithoutCommit();
finishTrustListImport();
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
} catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it.
identity = new OwnIdentity(this, insertFreenetURI, null, false);
Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity);
identity.restoreEdition(edition, null);
// Store the new identity
identity.storeWithoutCommit();
initTrustTreeWithoutCommit(identity);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity);
}
mFetcher.storeStartFetchCommandWithoutCommit(identity);
// This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards.
assert(computeAllScoresWithoutCommit());
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function
abortTrustListImport(e); // Does rollback for us
throw e;
} else {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
}
}
Logger.normal(this, "restoreOwnIdentity(): Finished.");
}
public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment)
throws UnknownIdentityException, NumberFormatException, InvalidParameterException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
Identity trustee = getIdentityByID(trusteeID);
setTrust(truster, trustee, value, comment);
}
public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException {
final OwnIdentity truster = getOwnIdentityByID(ownTrusterID);
final Identity trustee = getIdentityByID(trusteeID);
synchronized(mFetcher) {
synchronized(Persistent.transactionLock(mDB)) {
try {
removeTrustWithoutCommit(truster, trustee);
Persistent.checkedCommit(mDB, this);
}
catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
}
/**
* Enables or disables the publishing of the trust list of an {@link OwnIdentity}.
* The trust list contains all trust values which the OwnIdentity has assigned to other identities.
*
* @see OwnIdentity#setPublishTrustList(boolean)
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishTrustList Whether to publish the trust list.
* @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}.
*/
public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setPublishTrustList(publishTrustList);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e) {
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity);
}
/**
* Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}.
*
* If publishIntroductionPuzzles==true adds, if false removes:
* - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT}
* - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT}
*
* @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify.
* @param publishIntroductionPuzzles Whether to publish introduction puzzles.
* @throws UnknownIdentityException If there is no identity with the given ownIdentityID
* @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list.
*/
public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
if(!identity.doesPublishTrustList())
throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!");
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
if(publishIntroductionPuzzles) {
identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT));
} else {
identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT);
identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY);
}
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity);
}
public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.addContext(newContext);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeContext(context);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'");
}
public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException {
return getIdentityByID(identityID).getProperty(property);
}
public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.setProperty(property, value);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'");
}
public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException {
final OwnIdentity identity = getOwnIdentityByID(ownIdentityID);
final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager
synchronized(mSubscriptionManager) {
synchronized(Persistent.transactionLock(mDB)) {
try {
identity.removeProperty(property);
mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity);
identity.storeAndCommit();
} catch(RuntimeException e){
Persistent.checkedRollbackAndThrow(mDB, this, e);
}
}
}
if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'");
}
public String getVersion() {
return Version.getMarketingVersion();
}
public long getRealVersion() {
return Version.getRealVersion();
}
public String getString(String key) {
return getBaseL10n().getString(key);
}
public void setLanguage(LANGUAGE newLanguage) {
WebOfTrust.l10n = new PluginL10n(this, newLanguage);
if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode);
}
public PluginRespirator getPluginRespirator() {
return mPR;
}
public ExtObjectContainer getDatabase() {
return mDB;
}
public Configuration getConfig() {
return mConfig;
}
public SubscriptionManager getSubscriptionManager() {
return mSubscriptionManager;
}
public IdentityFetcher getIdentityFetcher() {
return mFetcher;
}
public XMLTransformer getXMLTransformer() {
return mXMLTransformer;
}
public IntroductionPuzzleStore getIntroductionPuzzleStore() {
return mPuzzleStore;
}
public IntroductionClient getIntroductionClient() {
return mIntroductionClient;
}
protected FCPInterface getFCPInterface() {
return mFCPInterface;
}
public RequestClient getRequestClient() {
return mRequestClient;
}
/**
* This is where our L10n files are stored.
* @return Path of our L10n files.
*/
public String getL10nFilesBasePath() {
return "plugins/WebOfTrust/l10n/";
}
/**
* This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ...
* @return Mask of the L10n files.
*/
public String getL10nFilesMask() {
return "lang_${lang}.l10n";
}
/**
* Override L10n files are stored on the disk, their names should be explicit
* we put here the plugin name, and the "override" indication. Plugin L10n
* override is not implemented in the node yet.
* @return Mask of the override L10n files.
*/
public String getL10nOverrideFilesMask() {
return "WebOfTrust_lang_${lang}.override.l10n";
}
/**
* Get the ClassLoader of this plugin. This is necessary when getting
* resources inside the plugin's Jar, for example L10n files.
* @return ClassLoader object
*/
public ClassLoader getPluginClassLoader() {
return WebOfTrust.class.getClassLoader();
}
/**
* Access to the current L10n data.
*
* @return L10n object.
*/
public BaseL10n getBaseL10n() {
return WebOfTrust.l10n.getBase();
}
public int getNumberOfFullScoreRecomputations() {
return mFullScoreRecomputationCount;
}
public synchronized double getAverageFullScoreRecomputationTime() {
return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000);
}
public int getNumberOfIncrementalScoreRecomputations() {
return mIncrementalScoreRecomputationCount;
}
public synchronized double getAverageIncrementalScoreRecomputationTime() {
return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000);
}
/**
* Tests whether two WoT are equal.
* This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests.
*/
public synchronized boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof WebOfTrust))
return false;
WebOfTrust other = (WebOfTrust)obj;
synchronized(other) {
{ // Compare own identities
final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities();
if(allIdentities.size() != other.getAllOwnIdentities().size())
return false;
for(OwnIdentity identity : allIdentities) {
try {
if(!identity.equals(other.getOwnIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare identities
final ObjectSet<Identity> allIdentities = getAllIdentities();
if(allIdentities.size() != other.getAllIdentities().size())
return false;
for(Identity identity : allIdentities) {
try {
if(!identity.equals(other.getIdentityByID(identity.getID())))
return false;
} catch(UnknownIdentityException e) {
return false;
}
}
}
{ // Compare trusts
final ObjectSet<Trust> allTrusts = getAllTrusts();
if(allTrusts.size() != other.getAllTrusts().size())
return false;
for(Trust trust : allTrusts) {
try {
Identity otherTruster = other.getIdentityByID(trust.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID());
if(!trust.equals(other.getTrust(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotTrustedException e) {
return false;
}
}
}
{ // Compare scores
final ObjectSet<Score> allScores = getAllScores();
if(allScores.size() != other.getAllScores().size())
return false;
for(Score score : allScores) {
try {
OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID());
Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID());
if(!score.equals(other.getScore(otherTruster, otherTrustee)))
return false;
} catch(UnknownIdentityException e) {
return false;
} catch(NotInTrustTreeException e) {
return false;
}
}
}
}
return true;
}
}
|
diff --git a/src/main/java/dk/frankbille/scoreboard/service/DefaultScoreBoardService.java b/src/main/java/dk/frankbille/scoreboard/service/DefaultScoreBoardService.java
index 06c3450..9d5b2da 100644
--- a/src/main/java/dk/frankbille/scoreboard/service/DefaultScoreBoardService.java
+++ b/src/main/java/dk/frankbille/scoreboard/service/DefaultScoreBoardService.java
@@ -1,164 +1,168 @@
package dk.frankbille.scoreboard.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import dk.frankbille.scoreboard.dao.GameDao;
import dk.frankbille.scoreboard.dao.PlayerDao;
import dk.frankbille.scoreboard.domain.Game;
import dk.frankbille.scoreboard.domain.GameTeam;
import dk.frankbille.scoreboard.domain.Player;
import dk.frankbille.scoreboard.domain.PlayerResult;
import dk.frankbille.scoreboard.domain.PlayerResult.Trend;
import dk.frankbille.scoreboard.ratings.RatingCalculator;
import dk.frankbille.scoreboard.ratings.RatingProvider;
@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class DefaultScoreBoardService implements ScoreBoardService {
private GameDao gameDao;
private PlayerDao playerDao;
@Autowired
public DefaultScoreBoardService(GameDao gameDao, PlayerDao playerDao) {
this.gameDao = gameDao;
this.playerDao = playerDao;
}
@Override
public Player createNewPlayer(String name) {
Player player = new Player();
player.setName(name);
playerDao.savePlayer(player);
return player;
}
@Override
public void savePlayer(Player player) {
playerDao.savePlayer(player);
}
@Transactional(readOnly=true)
@Override
public List<Player> getAllPlayers() {
return playerDao.getAllPlayers();
}
@Override
public void saveGame(Game game) {
gameDao.saveGame(game);
}
@Override
public List<Game> getAllGames() {
List<Game> games = gameDao.getAllGames();
RatingCalculator rating = RatingProvider.getRatings();
rating.setGames(games);
return games;
}
@Override
public List<Game> getPlayerGames(Player player) {
List<Game> playerGames = new ArrayList<Game>();
List<Game> allGames = getAllGames();
for (Game game : allGames) {
if (game.hasPlayer(player)) {
playerGames.add(game);
}
}
return playerGames;
}
@Override
public List<PlayerResult> getPlayerResults() {
List<PlayerResult> playerResults = new ArrayList<PlayerResult>();
Map<Player, PlayerResult> cache = new HashMap<Player, PlayerResult>();
Map<Player, List<Game>> playerGamesCache = new HashMap<Player, List<Game>>();
List<Game> games = gameDao.getAllGames();
for (Game game : games) {
List<GameTeam> gameTeams = game.getTeams();
for (GameTeam gameTeam : gameTeams) {
Set<Player> players = gameTeam.getTeam().getPlayers();
for (Player player : players) {
PlayerResult result = cache.get(player);
if (result == null) {
result = new PlayerResult(player);
cache.put(player, result);
playerResults.add(result);
}
List<Game> playerGames = playerGamesCache.get(player);
if (playerGames == null) {
playerGames = new ArrayList<Game>();
playerGamesCache.put(player, playerGames);
}
playerGames.add(game);
if (game.didTeamWin(gameTeam)) {
result.gameWon();
} else {
result.gameLost();
}
}
}
}
// Add trends
for (Player player : playerGamesCache.keySet()) {
List<Game> playerGames = playerGamesCache.get(player);
// Take the last 3 games
int trendPeriod = playerGames.size() < 3 ? playerGames.size() : 3;
if (playerGames.size() > 0) {
Collections.sort(playerGames, new Comparator<Game>() {
@Override
public int compare(Game o1, Game o2) {
- return o2.getDate().compareTo(o1.getDate());
+ int compare = o2.getDate().compareTo(o1.getDate());
+ if (compare == 0) {
+ compare = o2.getId().compareTo(o1.getId());
+ }
+ return compare;
}
});
int winCount = 0;
int looseCount = 0;
for (int i = 0; i < trendPeriod; i++) {
Game game = playerGames.get(i);
if (game.didPlayerWin(player)) {
winCount++;
} else {
looseCount++;
}
}
if (winCount > looseCount) {
cache.get(player).setTrend(Trend.WINNING);
} else if (winCount < looseCount) {
cache.get(player).setTrend(Trend.LOOSING);
} else {
cache.get(player).setTrend(Trend.EVEN);
}
} else {
cache.get(player).setTrend(Trend.NOT_DEFINED);
}
}
return playerResults;
}
@Override
public Player getPlayer(Long playerId) {
return playerDao.getPlayer(playerId);
}
}
| true | true | public List<PlayerResult> getPlayerResults() {
List<PlayerResult> playerResults = new ArrayList<PlayerResult>();
Map<Player, PlayerResult> cache = new HashMap<Player, PlayerResult>();
Map<Player, List<Game>> playerGamesCache = new HashMap<Player, List<Game>>();
List<Game> games = gameDao.getAllGames();
for (Game game : games) {
List<GameTeam> gameTeams = game.getTeams();
for (GameTeam gameTeam : gameTeams) {
Set<Player> players = gameTeam.getTeam().getPlayers();
for (Player player : players) {
PlayerResult result = cache.get(player);
if (result == null) {
result = new PlayerResult(player);
cache.put(player, result);
playerResults.add(result);
}
List<Game> playerGames = playerGamesCache.get(player);
if (playerGames == null) {
playerGames = new ArrayList<Game>();
playerGamesCache.put(player, playerGames);
}
playerGames.add(game);
if (game.didTeamWin(gameTeam)) {
result.gameWon();
} else {
result.gameLost();
}
}
}
}
// Add trends
for (Player player : playerGamesCache.keySet()) {
List<Game> playerGames = playerGamesCache.get(player);
// Take the last 3 games
int trendPeriod = playerGames.size() < 3 ? playerGames.size() : 3;
if (playerGames.size() > 0) {
Collections.sort(playerGames, new Comparator<Game>() {
@Override
public int compare(Game o1, Game o2) {
return o2.getDate().compareTo(o1.getDate());
}
});
int winCount = 0;
int looseCount = 0;
for (int i = 0; i < trendPeriod; i++) {
Game game = playerGames.get(i);
if (game.didPlayerWin(player)) {
winCount++;
} else {
looseCount++;
}
}
if (winCount > looseCount) {
cache.get(player).setTrend(Trend.WINNING);
} else if (winCount < looseCount) {
cache.get(player).setTrend(Trend.LOOSING);
} else {
cache.get(player).setTrend(Trend.EVEN);
}
} else {
cache.get(player).setTrend(Trend.NOT_DEFINED);
}
}
return playerResults;
}
| public List<PlayerResult> getPlayerResults() {
List<PlayerResult> playerResults = new ArrayList<PlayerResult>();
Map<Player, PlayerResult> cache = new HashMap<Player, PlayerResult>();
Map<Player, List<Game>> playerGamesCache = new HashMap<Player, List<Game>>();
List<Game> games = gameDao.getAllGames();
for (Game game : games) {
List<GameTeam> gameTeams = game.getTeams();
for (GameTeam gameTeam : gameTeams) {
Set<Player> players = gameTeam.getTeam().getPlayers();
for (Player player : players) {
PlayerResult result = cache.get(player);
if (result == null) {
result = new PlayerResult(player);
cache.put(player, result);
playerResults.add(result);
}
List<Game> playerGames = playerGamesCache.get(player);
if (playerGames == null) {
playerGames = new ArrayList<Game>();
playerGamesCache.put(player, playerGames);
}
playerGames.add(game);
if (game.didTeamWin(gameTeam)) {
result.gameWon();
} else {
result.gameLost();
}
}
}
}
// Add trends
for (Player player : playerGamesCache.keySet()) {
List<Game> playerGames = playerGamesCache.get(player);
// Take the last 3 games
int trendPeriod = playerGames.size() < 3 ? playerGames.size() : 3;
if (playerGames.size() > 0) {
Collections.sort(playerGames, new Comparator<Game>() {
@Override
public int compare(Game o1, Game o2) {
int compare = o2.getDate().compareTo(o1.getDate());
if (compare == 0) {
compare = o2.getId().compareTo(o1.getId());
}
return compare;
}
});
int winCount = 0;
int looseCount = 0;
for (int i = 0; i < trendPeriod; i++) {
Game game = playerGames.get(i);
if (game.didPlayerWin(player)) {
winCount++;
} else {
looseCount++;
}
}
if (winCount > looseCount) {
cache.get(player).setTrend(Trend.WINNING);
} else if (winCount < looseCount) {
cache.get(player).setTrend(Trend.LOOSING);
} else {
cache.get(player).setTrend(Trend.EVEN);
}
} else {
cache.get(player).setTrend(Trend.NOT_DEFINED);
}
}
return playerResults;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugContentProvider.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugContentProvider.java
index 0df8836dd..a10672c7e 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugContentProvider.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugContentProvider.java
@@ -1,141 +1,139 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IStackFrame;
import org.eclipse.debug.ui.DefaultDebugViewContentProvider;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
/**
* Java debugger content provider for the debug view. Provides monitor
* information.
*
* @since 3.1
*/
public class JavaDebugContentProvider extends DefaultDebugViewContentProvider implements IPropertyChangeListener {
private boolean fDisplayMonitors= false;
public JavaDebugContentProvider() {
IPreferenceStore preferenceStore = JDIDebugUIPlugin.getDefault().getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
fDisplayMonitors= preferenceStore.getBoolean(IJDIPreferencesConstants.PREF_SHOW_MONITOR_THREAD_INFO);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
public Object[] getChildren(Object parent) {
try {
if (fDisplayMonitors && parent instanceof IJavaThread) {
IJavaThread thread= (IJavaThread)parent;
ThreadMonitorManager threadMonitorManager= ThreadMonitorManager.getDefault();
JavaOwnedMonitor[] ownedMonitors= threadMonitorManager.getOwnedMonitors(thread);
JavaContendedMonitor contendedMonitor= threadMonitorManager.getContendedMonitor(thread);
IStackFrame[] stackFrames= thread.getStackFrames();
Object[] children= new Object[ownedMonitors.length + (contendedMonitor == null ? 0 : 1) + stackFrames.length];
int k= 0;
for (int i= 0; i < ownedMonitors.length; i++) {
children[k++]= ownedMonitors[i];
}
if (contendedMonitor != null) {
children[k++]= contendedMonitor;
}
for (int i= 0; i < stackFrames.length; i++) {
children[k++]= stackFrames[i];
}
return children;
}
if (parent instanceof JavaOwnedMonitor) {
return ((JavaOwnedMonitor)parent).getWaitingThreads();
}
if (parent instanceof JavaContendedMonitor) {
JavaOwningThread owningThread= ((JavaContendedMonitor)parent).getOwningThread();
if (owningThread != null) {
return new Object[] {owningThread};
}
}
if (parent instanceof JavaWaitingThread) {
return ((JavaWaitingThread)parent).getOwnedMonitors();
}
if (parent instanceof JavaOwningThread) {
JavaContendedMonitor contendedMonitor= ((JavaOwningThread)parent).getContendedMonitor();
if (contendedMonitor != null) {
return new Object[] {contendedMonitor};
}
}
} catch (DebugException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
}
return super.getChildren(parent);
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.DefaultDebugViewContentProvider#hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object element) {
if (element instanceof JavaOwnedMonitor) {
return ((JavaOwnedMonitor)element).getWaitingThreads().length > 0;
}
if (element instanceof JavaContendedMonitor) {
return ((JavaContendedMonitor)element).getOwningThread() != null;
}
if (element instanceof JavaOwningThread) {
return ((JavaOwningThread)element).getContendedMonitor() != null;
}
if (element instanceof JavaWaitingThread) {
return ((JavaWaitingThread)element).getOwnedMonitors().length > 0;
}
return super.hasChildren(element);
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.DefaultDebugViewContentProvider#getParent(java.lang.Object)
*/
public Object getParent(Object element) {
if (element instanceof JavaOwnedMonitor) {
JavaWaitingThread parent= ((JavaOwnedMonitor)element).getParent();
if (parent.getParent() == null) {
return parent.getThread();
}
return parent;
}
if (element instanceof JavaContendedMonitor) {
JavaOwningThread parent= ((JavaContendedMonitor) element).getParent();
if (parent.getParent() == null) {
return parent.getThread();
}
return parent;
}
if (element instanceof JavaOwningThread) {
return ((JavaOwningThread)element).getParent();
}
if (element instanceof JavaWaitingThread) {
return ((JavaWaitingThread)element).getParent();
}
return super.getParent(element);
}
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IJDIPreferencesConstants.PREF_SHOW_MONITOR_THREAD_INFO)) {
fDisplayMonitors= ((Boolean)event.getNewValue()).booleanValue();
}
}
}
| true | true | public Object[] getChildren(Object parent) {
try {
if (fDisplayMonitors && parent instanceof IJavaThread) {
IJavaThread thread= (IJavaThread)parent;
ThreadMonitorManager threadMonitorManager= ThreadMonitorManager.getDefault();
JavaOwnedMonitor[] ownedMonitors= threadMonitorManager.getOwnedMonitors(thread);
JavaContendedMonitor contendedMonitor= threadMonitorManager.getContendedMonitor(thread);
IStackFrame[] stackFrames= thread.getStackFrames();
Object[] children= new Object[ownedMonitors.length + (contendedMonitor == null ? 0 : 1) + stackFrames.length];
int k= 0;
for (int i= 0; i < ownedMonitors.length; i++) {
children[k++]= ownedMonitors[i];
}
if (contendedMonitor != null) {
children[k++]= contendedMonitor;
}
for (int i= 0; i < stackFrames.length; i++) {
children[k++]= stackFrames[i];
}
return children;
}
if (parent instanceof JavaOwnedMonitor) {
return ((JavaOwnedMonitor)parent).getWaitingThreads();
}
if (parent instanceof JavaContendedMonitor) {
JavaOwningThread owningThread= ((JavaContendedMonitor)parent).getOwningThread();
if (owningThread != null) {
return new Object[] {owningThread};
}
}
if (parent instanceof JavaWaitingThread) {
return ((JavaWaitingThread)parent).getOwnedMonitors();
}
if (parent instanceof JavaOwningThread) {
JavaContendedMonitor contendedMonitor= ((JavaOwningThread)parent).getContendedMonitor();
if (contendedMonitor != null) {
return new Object[] {contendedMonitor};
}
}
} catch (DebugException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.getChildren(parent);
}
| public Object[] getChildren(Object parent) {
try {
if (fDisplayMonitors && parent instanceof IJavaThread) {
IJavaThread thread= (IJavaThread)parent;
ThreadMonitorManager threadMonitorManager= ThreadMonitorManager.getDefault();
JavaOwnedMonitor[] ownedMonitors= threadMonitorManager.getOwnedMonitors(thread);
JavaContendedMonitor contendedMonitor= threadMonitorManager.getContendedMonitor(thread);
IStackFrame[] stackFrames= thread.getStackFrames();
Object[] children= new Object[ownedMonitors.length + (contendedMonitor == null ? 0 : 1) + stackFrames.length];
int k= 0;
for (int i= 0; i < ownedMonitors.length; i++) {
children[k++]= ownedMonitors[i];
}
if (contendedMonitor != null) {
children[k++]= contendedMonitor;
}
for (int i= 0; i < stackFrames.length; i++) {
children[k++]= stackFrames[i];
}
return children;
}
if (parent instanceof JavaOwnedMonitor) {
return ((JavaOwnedMonitor)parent).getWaitingThreads();
}
if (parent instanceof JavaContendedMonitor) {
JavaOwningThread owningThread= ((JavaContendedMonitor)parent).getOwningThread();
if (owningThread != null) {
return new Object[] {owningThread};
}
}
if (parent instanceof JavaWaitingThread) {
return ((JavaWaitingThread)parent).getOwnedMonitors();
}
if (parent instanceof JavaOwningThread) {
JavaContendedMonitor contendedMonitor= ((JavaOwningThread)parent).getContendedMonitor();
if (contendedMonitor != null) {
return new Object[] {contendedMonitor};
}
}
} catch (DebugException e) {
}
return super.getChildren(parent);
}
|
diff --git a/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingController.java b/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingController.java
index c3c66cc..e860a02 100644
--- a/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingController.java
+++ b/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingController.java
@@ -1,53 +1,53 @@
/*
* JSR 354 JavaFX Binding Example
*/
package net.java.javamoney.examples.javafx;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Werner Keil
*
*/
public class BindingController
{
private static final Logger log = LoggerFactory.getLogger(BindingController.class);
@FXML private TextField firstNameField;
@FXML private TextField lastNameField;
@FXML private Label messageLabel;
public void sayHello() {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
StringBuilder builder = new StringBuilder();
if (!StringUtils.isEmpty(firstName)) {
builder.append(firstName);
}
if (!StringUtils.isEmpty(lastName)) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(lastName);
}
if (builder.length() > 0) {
String name = builder.toString();
log.debug("Saying hello to " + name);
messageLabel.setText("Hello " + name);
} else {
- log.debug("Neither first name nor last name was set, saying hello to anonymous person");
- messageLabel.setText("Hello mysterious person");
+ log.debug("Neither first name nor last name was set, cannot create account for anonymous person");
+ messageLabel.setText("Sorry mysterious person;-)");
}
}
}
| true | true | public void sayHello() {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
StringBuilder builder = new StringBuilder();
if (!StringUtils.isEmpty(firstName)) {
builder.append(firstName);
}
if (!StringUtils.isEmpty(lastName)) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(lastName);
}
if (builder.length() > 0) {
String name = builder.toString();
log.debug("Saying hello to " + name);
messageLabel.setText("Hello " + name);
} else {
log.debug("Neither first name nor last name was set, saying hello to anonymous person");
messageLabel.setText("Hello mysterious person");
}
}
| public void sayHello() {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
StringBuilder builder = new StringBuilder();
if (!StringUtils.isEmpty(firstName)) {
builder.append(firstName);
}
if (!StringUtils.isEmpty(lastName)) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(lastName);
}
if (builder.length() > 0) {
String name = builder.toString();
log.debug("Saying hello to " + name);
messageLabel.setText("Hello " + name);
} else {
log.debug("Neither first name nor last name was set, cannot create account for anonymous person");
messageLabel.setText("Sorry mysterious person;-)");
}
}
|
diff --git a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
index e34443b..3f05ebe 100644
--- a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
+++ b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
@@ -1,208 +1,213 @@
/*******************************************************************************
* Copyright (c) 2013 Red Hat, Inc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mickael Istria (Red Hat) - initial API and implementation
*******************************************************************************/
package org.jboss.tools.tycho.targets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.Logger;
import org.eclipse.sisu.equinox.EquinoxServiceFactory;
import org.eclipse.tycho.artifacts.TargetPlatform;
import org.eclipse.tycho.core.resolver.shared.MavenRepositoryLocation;
import org.eclipse.tycho.osgi.adapters.MavenLoggerAdapter;
import org.eclipse.tycho.p2.resolver.TargetDefinitionFile;
import org.eclipse.tycho.p2.resolver.facade.P2ResolutionResult;
import org.eclipse.tycho.p2.resolver.facade.P2Resolver;
import org.eclipse.tycho.p2.resolver.facade.P2ResolverFactory;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.InstallableUnitLocation;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Location;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Repository;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Unit;
import org.eclipse.tycho.p2.target.facade.TargetPlatformBuilder;
import org.osgi.framework.Version;
/**
*
* @goal fix-versions
* @requireProject false
* @author mistria
*
*/
public class FixVersionsMojo extends AbstractMojo {
/**
* .target file to fix version
*
* @parameter expression="${targetFile}"
*/
private File targetFile;
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/** @component */
protected EquinoxServiceFactory equinox;
/** @component */
private Logger plexusLogger;
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.targetFile == null) {
if (this.project != null && this.project.getPackaging().equals("eclipse-target-definition")) {
this.targetFile = new File(this.project.getBasedir(), this.project.getArtifactId() + ".target");
}
}
if (this.targetFile == null) {
throw new MojoFailureException("You need to set a <targetFile/> for packaging types that are not 'eclipse-target-definition'");
}
if (!this.targetFile.isFile()) {
throw new MojoFailureException("Specified target file " + this.targetFile.getAbsolutePath() + " is not a valid file");
}
File outputFile = new File(targetFile.getParentFile(), targetFile.getName() + "_update_hints.txt");
FileOutputStream fos = null;
try {
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
TargetDefinitionFile targetDef;
try {
targetDef = TargetDefinitionFile.read(this.targetFile);
} catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
for (Location location : targetDef.getLocations()) {
if (!(location instanceof InstallableUnitLocation)) {
getLog().warn("Location type " + location.getClass().getSimpleName() + " not supported");
continue;
}
InstallableUnitLocation loc = (InstallableUnitLocation) location;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : loc.getRepositories()) {
String id = repo.getId();
if (repo.getId() == null || repo.getId().isEmpty()) {
id = repo.getLocation().toString();
}
tpBuilder.addP2Repository(new MavenRepositoryLocation(id, repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : loc.getUnits()) {
getLog().info("checking " + unit.getId());
String version = findBestMatchingVersion(site, resolver, unit);
if (!version.equals(unit.getVersion())) {
String message = unit.getId() + " ->" + version;
getLog().info(message);
fos.write(message.getBytes());
fos.write('\n');
}
+ if (unit instanceof TargetDefinitionFile.Unit) {
+ // That's deprecated, but so cool (and no other way to do it except doing parsing by hand)
+ ((TargetDefinitionFile.Unit)unit).setVersion(version);
+ }
}
}
+ TargetDefinitionFile.write(targetDef, new File(targetFile.getParent(), targetFile.getName() + "_fixedVersion.target"));
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error while opening output file " + outputFile, ex);
} catch (IOException ex) {
throw new MojoExecutionException("Can't write to file " + outputFile, ex);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception ex) {
throw new MojoExecutionException("IO error", ex);
}
}
}
}
private String findBestMatchingVersion(TargetPlatform site, P2Resolver resolver, Unit unit) throws MojoFailureException, MojoExecutionException {
String version = unit.getVersion();
P2ResolutionResult currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryExactVersion(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreQualifier(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreMicro(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreMinor(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), "0.0.0");
}
}
}
}
if (currentIUResult.getArtifacts().size() > 0) {
return currentIUResult.getArtifacts().iterator().next().getVersion();
} else if (currentIUResult.getNonReactorUnits().size() > 0) {
Object foundItem = currentIUResult.getNonReactorUnits().iterator().next();
// foundItem is most probably a p2 internal InstallableUnit (type not accessible from Tycho). Let's do some introspection
try {
Method getVersionMethod = foundItem.getClass().getMethod("getVersion");
Object foundVersion = getVersionMethod.invoke(foundItem);
return foundVersion.toString();
} catch (Exception ex) {
throw new MojoExecutionException("Unsupported search result " + foundItem.getClass(), ex);
}
} else {
throw new MojoFailureException("Could not find any IU for " + unit.getId());
}
}
private String toQueryExactVersion(String version) {
return "[" + version + "," + version + "]";
}
private String toQueryIgnoreMinor(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append(".0.0");
res.append(",");
res.append(osgiVersion.getMajor() + 1); res.append(".0.0");
res.append(")");
return res.toString();
}
private String toQueryIgnoreMicro(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append(".0");
res.append(",");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor() + 1); res.append(".0");
res.append(")");
return res.toString();
}
private String toQueryIgnoreQualifier(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append("."); res.append(osgiVersion.getMicro());
res.append(",");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append("."); res.append(osgiVersion.getMicro() + 1);
res.append(")");
return res.toString();
}
}
| false | true | public void execute() throws MojoExecutionException, MojoFailureException {
if (this.targetFile == null) {
if (this.project != null && this.project.getPackaging().equals("eclipse-target-definition")) {
this.targetFile = new File(this.project.getBasedir(), this.project.getArtifactId() + ".target");
}
}
if (this.targetFile == null) {
throw new MojoFailureException("You need to set a <targetFile/> for packaging types that are not 'eclipse-target-definition'");
}
if (!this.targetFile.isFile()) {
throw new MojoFailureException("Specified target file " + this.targetFile.getAbsolutePath() + " is not a valid file");
}
File outputFile = new File(targetFile.getParentFile(), targetFile.getName() + "_update_hints.txt");
FileOutputStream fos = null;
try {
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
TargetDefinitionFile targetDef;
try {
targetDef = TargetDefinitionFile.read(this.targetFile);
} catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
for (Location location : targetDef.getLocations()) {
if (!(location instanceof InstallableUnitLocation)) {
getLog().warn("Location type " + location.getClass().getSimpleName() + " not supported");
continue;
}
InstallableUnitLocation loc = (InstallableUnitLocation) location;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : loc.getRepositories()) {
String id = repo.getId();
if (repo.getId() == null || repo.getId().isEmpty()) {
id = repo.getLocation().toString();
}
tpBuilder.addP2Repository(new MavenRepositoryLocation(id, repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : loc.getUnits()) {
getLog().info("checking " + unit.getId());
String version = findBestMatchingVersion(site, resolver, unit);
if (!version.equals(unit.getVersion())) {
String message = unit.getId() + " ->" + version;
getLog().info(message);
fos.write(message.getBytes());
fos.write('\n');
}
}
}
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error while opening output file " + outputFile, ex);
} catch (IOException ex) {
throw new MojoExecutionException("Can't write to file " + outputFile, ex);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception ex) {
throw new MojoExecutionException("IO error", ex);
}
}
}
}
| public void execute() throws MojoExecutionException, MojoFailureException {
if (this.targetFile == null) {
if (this.project != null && this.project.getPackaging().equals("eclipse-target-definition")) {
this.targetFile = new File(this.project.getBasedir(), this.project.getArtifactId() + ".target");
}
}
if (this.targetFile == null) {
throw new MojoFailureException("You need to set a <targetFile/> for packaging types that are not 'eclipse-target-definition'");
}
if (!this.targetFile.isFile()) {
throw new MojoFailureException("Specified target file " + this.targetFile.getAbsolutePath() + " is not a valid file");
}
File outputFile = new File(targetFile.getParentFile(), targetFile.getName() + "_update_hints.txt");
FileOutputStream fos = null;
try {
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
TargetDefinitionFile targetDef;
try {
targetDef = TargetDefinitionFile.read(this.targetFile);
} catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
for (Location location : targetDef.getLocations()) {
if (!(location instanceof InstallableUnitLocation)) {
getLog().warn("Location type " + location.getClass().getSimpleName() + " not supported");
continue;
}
InstallableUnitLocation loc = (InstallableUnitLocation) location;
TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(new MockExecutionEnvironment());
for (Repository repo : loc.getRepositories()) {
String id = repo.getId();
if (repo.getId() == null || repo.getId().isEmpty()) {
id = repo.getLocation().toString();
}
tpBuilder.addP2Repository(new MavenRepositoryLocation(id, repo.getLocation()));
}
TargetPlatform site = tpBuilder.buildTargetPlatform();
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : loc.getUnits()) {
getLog().info("checking " + unit.getId());
String version = findBestMatchingVersion(site, resolver, unit);
if (!version.equals(unit.getVersion())) {
String message = unit.getId() + " ->" + version;
getLog().info(message);
fos.write(message.getBytes());
fos.write('\n');
}
if (unit instanceof TargetDefinitionFile.Unit) {
// That's deprecated, but so cool (and no other way to do it except doing parsing by hand)
((TargetDefinitionFile.Unit)unit).setVersion(version);
}
}
}
TargetDefinitionFile.write(targetDef, new File(targetFile.getParent(), targetFile.getName() + "_fixedVersion.target"));
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error while opening output file " + outputFile, ex);
} catch (IOException ex) {
throw new MojoExecutionException("Can't write to file " + outputFile, ex);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception ex) {
throw new MojoExecutionException("IO error", ex);
}
}
}
}
|
diff --git a/src/wsc_application/WilliamsSpecialtyGUI.java b/src/wsc_application/WilliamsSpecialtyGUI.java
index dea08ab..e1ff6b8 100644
--- a/src/wsc_application/WilliamsSpecialtyGUI.java
+++ b/src/wsc_application/WilliamsSpecialtyGUI.java
@@ -1,3028 +1,3028 @@
package wsc_application;
/**
* CIS470 Senior Project
* Williams Specialty
* Business Automation Project
*
* Group A:
*
* Basic GUI Layout &
* Order Verify Tab Events &
* Quality Assurance Tab Events &
* User Access Level Events
* through Login/Logout
* Created by Brad Clawson
*
* GUI Modifications &
* Employee Tab Events &
* Customer Tab Events
* Created by Jacob Savage
*
* GUI Modifications &
* Order Tab Events &
* Login Tab Events
* Created by Paul Durivage
*
* GUI Modifications &
* Inventory Tab Events
* Created by Joshua Petersen
**/
import java.awt.Color;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import static javax.swing.JComponent.TOOL_TIP_TEXT_KEY;
import javax.swing.JList;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.*;
public class WilliamsSpecialtyGUI extends javax.swing.JPanel{
// protected Order order;
protected ArrayList<Order> orders;
public WilliamsSpecialtyGUI() {
initComponents();
HideEmpPassword();
/* //Brad: make all tabs except login invisible Login action will set user access
* CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/ }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
OrderPayTypeBG = new javax.swing.ButtonGroup();
OrderTypeBG = new javax.swing.ButtonGroup();
OrderEngMediaBG = new javax.swing.ButtonGroup();
OVAccountBG = new javax.swing.ButtonGroup();
OVNameBG = new javax.swing.ButtonGroup();
QAContentBG = new javax.swing.ButtonGroup();
QAMediaBG = new javax.swing.ButtonGroup();
QAMediaFinishBG = new javax.swing.ButtonGroup();
QAWorkmanshipBG = new javax.swing.ButtonGroup();
OVMediaBG = new javax.swing.ButtonGroup();
OVContentBG = new javax.swing.ButtonGroup();
OVPaymentBG = new javax.swing.ButtonGroup();
OVDepositBG = new javax.swing.ButtonGroup();
WSCInterface = new javax.swing.JTabbedPane();
LoginPanel = new javax.swing.JPanel();
LoginButton = new javax.swing.JButton();
LoginEMPIDTxt = new javax.swing.JTextField();
LoginEMPIDLbl = new javax.swing.JLabel();
LoginPassLbl = new javax.swing.JLabel();
LoginPassText = new javax.swing.JPasswordField();
LogoutButton = new javax.swing.JButton();
lblLoginStatus = new javax.swing.JLabel();
CustomerInfoPanel = new javax.swing.JPanel();
CustFNameText = new javax.swing.JTextField();
CustLNameText = new javax.swing.JTextField();
CustOrgText = new javax.swing.JTextField();
CustStreet1Text = new javax.swing.JTextField();
CustStreet2Text = new javax.swing.JTextField();
CustFNameLbl = new javax.swing.JLabel();
CustLNameLbl = new javax.swing.JLabel();
CustOrgLbl = new javax.swing.JLabel();
CustStreet1Lbl = new javax.swing.JLabel();
CustStreet2Lbl = new javax.swing.JLabel();
CustCityText = new javax.swing.JTextField();
CustZipText = new javax.swing.JTextField();
CustCityLbl = new javax.swing.JLabel();
CustZipLbl = new javax.swing.JLabel();
CustFindButton = new javax.swing.JButton();
CustCreateButton = new javax.swing.JButton();
CustOrderListBox = new javax.swing.JScrollPane();
custOrdLst = new javax.swing.JList();
CustOrderListBoxLbl = new javax.swing.JLabel();
CustClearButton = new javax.swing.JButton();
CustActiveOrderLbl = new javax.swing.JLabel();
CUSTIDLbl = new javax.swing.JLabel();
CustStateCB = new javax.swing.JComboBox();
CustStateLbl = new javax.swing.JLabel();
InvSearchLbl5 = new javax.swing.JLabel();
CustPhoneLbl = new javax.swing.JLabel();
CustPhoneText = new javax.swing.JTextField();
CustEmailLbl = new javax.swing.JLabel();
CustEmailText = new javax.swing.JTextField();
CUSTIDCB = new javax.swing.JTextField();
OrderTabbedPane = new javax.swing.JTabbedPane();
OrderInfoPanel = new javax.swing.JPanel();
OrderNumberLbl = new javax.swing.JLabel();
OrderDeliverPayRB = new javax.swing.JRadioButton();
OrderAccountPayRB = new javax.swing.JRadioButton();
OrderDepositLbl = new javax.swing.JLabel();
OrderDepositText = new javax.swing.JTextField();
OrderTypeShirtRB = new javax.swing.JRadioButton();
OrderTypeTrophyRB = new javax.swing.JRadioButton();
OrderTypePlaqueRB = new javax.swing.JRadioButton();
OrderContentLbl = new javax.swing.JLabel();
OrderContentText = new javax.swing.JTextField();
OrderMediaCatNumLbl = new javax.swing.JLabel();
OrderMediaCatNumText = new javax.swing.JTextField();
OrderMediaTypeLbl = new javax.swing.JLabel();
OrderCustNumberLbl = new javax.swing.JLabel();
OrderCUSTIDText = new javax.swing.JTextField();
OrderPaymentTypeLbl = new javax.swing.JLabel();
OrderClearFieldsButton = new javax.swing.JButton();
OrderCreateBtn = new javax.swing.JButton();
OrderSearchButton = new javax.swing.JButton();
OrderMediaStatusCB = new javax.swing.JComboBox();
OrderStatusLbl = new javax.swing.JLabel();
OrderStatusCB = new javax.swing.JComboBox();
OrderMediaStatusLbl = new javax.swing.JLabel();
OrderTotalLbl = new javax.swing.JLabel();
OrderTotalText = new javax.swing.JTextField();
OrderVerifyByLbl = new javax.swing.JLabel();
OrderAssignedToLbl = new javax.swing.JLabel();
OrderCreatedByLbl = new javax.swing.JLabel();
OrderNumberCB = new javax.swing.JComboBox();
OrderSearchLbl = new javax.swing.JLabel();
OrderUpdateBtn = new javax.swing.JButton();
OrderVerifyPanel = new javax.swing.JPanel();
OVSubmitButton = new javax.swing.JButton();
OVClearFieldButton = new javax.swing.JButton();
OVSearchButton = new javax.swing.JButton();
OVCorrectNameLbl = new javax.swing.JLabel();
OVAcctNumLbl = new javax.swing.JLabel();
OVMediaNumLbl = new javax.swing.JLabel();
OVContentLbl = new javax.swing.JLabel();
OVCorrectNamePassRb = new javax.swing.JRadioButton();
OVAcctNumPassRb = new javax.swing.JRadioButton();
OVMediaNumPassRb = new javax.swing.JRadioButton();
OVContentPassRb = new javax.swing.JRadioButton();
OVCorrectNameFailRb = new javax.swing.JRadioButton();
OVAcctNumFailRb = new javax.swing.JRadioButton();
OVMediaNumFailRb = new javax.swing.JRadioButton();
OVContentFailRb = new javax.swing.JRadioButton();
OVCommentsTB = new javax.swing.JScrollPane();
OVCommentsText = new javax.swing.JTextArea();
OVCommentsLbl = new javax.swing.JLabel();
OVNameFailText = new javax.swing.JTextField();
OVAcctNumFailText = new javax.swing.JTextField();
OVMediaFailText = new javax.swing.JTextField();
OVContentFailText = new javax.swing.JTextField();
OVPassLbl = new javax.swing.JLabel();
OVFailLbl = new javax.swing.JLabel();
OVReasonLbl = new javax.swing.JLabel();
OVDepositPassRb = new javax.swing.JRadioButton();
OVDepositLbl = new javax.swing.JLabel();
OVDepositFailRb = new javax.swing.JRadioButton();
OVPayTypeFailRb = new javax.swing.JRadioButton();
OVPayTypePassLbl = new javax.swing.JLabel();
OVDepositFailText = new javax.swing.JTextField();
OVPayTypeFailText = new javax.swing.JTextField();
OVPayTypePassRb = new javax.swing.JRadioButton();
OVNumberLbl = new javax.swing.JLabel();
OVerIDText = new javax.swing.JTextField();
OVCustNameValLbl = new javax.swing.JLabel();
OVCustIDValLbl = new javax.swing.JLabel();
OVMediaCatValLbl = new javax.swing.JLabel();
OVContentValLbl = new javax.swing.JLabel();
OVPayTypeValLbl = new javax.swing.JLabel();
OVDepositValLbl = new javax.swing.JLabel();
OVAssignEmpCB = new javax.swing.JComboBox();
OVAssignEmpLbl = new javax.swing.JLabel();
OVOrderNumLbl = new javax.swing.JLabel();
OVOrderIDText = new javax.swing.JTextField();
OVVerifyByLbl = new javax.swing.JLabel();
OVCreateByLbl = new javax.swing.JLabel();
OVAssignedToLbl = new javax.swing.JLabel();
OVButtonLbl = new javax.swing.JLabel();
QAPanel = new javax.swing.JPanel();
QASubmitButton = new javax.swing.JButton();
QAClearButton = new javax.swing.JButton();
QASearchButton = new javax.swing.JButton();
QAContentLbl = new javax.swing.JLabel();
QAMediaLbl = new javax.swing.JLabel();
QAMediaFinishLbl = new javax.swing.JLabel();
QAWorkmanshipLbl = new javax.swing.JLabel();
QAContentCheckPassRb = new javax.swing.JRadioButton();
QAMediaCheckPassRb = new javax.swing.JRadioButton();
QAMediaFinishCheckPassRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckPassRb = new javax.swing.JRadioButton();
QAContentCheckFailRb = new javax.swing.JRadioButton();
QAMediaCheckFailRb = new javax.swing.JRadioButton();
QAMediaFinishCheckFailRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckFailRb = new javax.swing.JRadioButton();
QACorrectiveActionTB = new javax.swing.JScrollPane();
QACorrectiveActionText = new javax.swing.JTextArea();
QACommentLbl = new javax.swing.JLabel();
QAContentFailText = new javax.swing.JTextField();
QAMediaFailText = new javax.swing.JTextField();
QAMediaFinishFailText = new javax.swing.JTextField();
QAWorkmanshipFailText = new javax.swing.JTextField();
QAPassLbl = new javax.swing.JLabel();
QAFailLbl = new javax.swing.JLabel();
QAFailCommentLbl = new javax.swing.JLabel();
QAVerifiedByLbl = new javax.swing.JLabel();
QACreatedByLbl = new javax.swing.JLabel();
QAAssignedToLbl = new javax.swing.JLabel();
QAOrderIDLbl = new javax.swing.JLabel();
QAIDLbl = new javax.swing.JLabel();
QAButtonLbl = new javax.swing.JLabel();
QAOrderIDText = new javax.swing.JTextField();
QAIDText = new javax.swing.JTextField();
InventoryPanel = new javax.swing.JPanel();
InvItemIDLbl = new javax.swing.JLabel();
InvManufacturerIdLbl = new javax.swing.JLabel();
InvQtyOnHandLbl = new javax.swing.JLabel();
InvQtyOnOrderLbl = new javax.swing.JLabel();
InvDeliveryDateLbl = new javax.swing.JLabel();
InvOrderButton = new javax.swing.JButton();
InvClearButton = new javax.swing.JButton();
InvSearchButton = new javax.swing.JButton();
InvItemNameLbl = new javax.swing.JLabel();
InvItemNameText = new javax.swing.JTextField();
InvButtonLbl = new javax.swing.JLabel();
InvOnHandText = new javax.swing.JTextField();
InvOnOrderText = new javax.swing.JTextField();
InvDeliveryDateText = new javax.swing.JTextField();
InvItemIdText = new javax.swing.JTextField();
InvManufacturerIdText = new javax.swing.JTextField();
InvOrderIdLbl = new javax.swing.JLabel();
InvOrderIdText = new javax.swing.JTextField();
InvManufacturerItemScrollPane = new javax.swing.JScrollPane();
InvManufacturerItemList = new javax.swing.JList();
InvManufacturerItemLbl = new javax.swing.JLabel();
EmployeeInfoPanel = new javax.swing.JPanel();
EmpFNameText = new javax.swing.JTextField();
EmpLNameText = new javax.swing.JTextField();
EmpFNameLbl = new javax.swing.JLabel();
EmpLNameLbl = new javax.swing.JLabel();
EmpSearchButton = new javax.swing.JButton();
EmpSubmitButton = new javax.swing.JButton();
EmpOrderLB = new javax.swing.JScrollPane();
emOrdersLst = new javax.swing.JList();
EmpOrderLbl = new javax.swing.JLabel();
EmpClearButton = new javax.swing.JButton();
EmpActiveOrderLbl1 = new javax.swing.JLabel();
EMPIDLbl = new javax.swing.JLabel();
EmpTypeCB = new javax.swing.JComboBox();
EmpTypeLbl = new javax.swing.JLabel();
EmpSearchLbl = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
EmpEmail = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
EmpPass = new javax.swing.JPasswordField();
jLabel4 = new javax.swing.JLabel();
EmpPassConfirm = new javax.swing.JPasswordField();
EMPIDCB = new javax.swing.JTextField();
setPreferredSize(new java.awt.Dimension(600, 549));
WSCInterface.setPreferredSize(new java.awt.Dimension(600, 549));
LoginPanel.setDoubleBuffered(false);
LoginButton.setText("Login");
LoginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginButtonActionPerformed(evt);
}
});
LoginEMPIDTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginEMPIDTxtActionPerformed(evt);
}
});
LoginEMPIDLbl.setText("Employee ID");
LoginPassLbl.setText("Password");
LoginPassText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginPassTextActionPerformed(evt);
}
});
LogoutButton.setText("Logout");
LogoutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogoutButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout LoginPanelLayout = new javax.swing.GroupLayout(LoginPanel);
LoginPanel.setLayout(LoginPanelLayout);
LoginPanelLayout.setHorizontalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(260, 260, 260)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, LoginPanelLayout.createSequentialGroup()
.addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(LogoutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginPassLbl))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LoginEMPIDTxt)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblLoginStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(199, Short.MAX_VALUE))
);
LoginPanelLayout.setVerticalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(157, 157, 157)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginEMPIDTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginPassLbl)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblLoginStatus))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LogoutButton)
.addComponent(LoginButton))
.addContainerGap(388, Short.MAX_VALUE))
);
WSCInterface.addTab("Login", LoginPanel);
CustFNameLbl.setText("First Name");
CustLNameLbl.setText("Last Name");
CustOrgLbl.setText("Organization");
CustStreet1Lbl.setText("Street Address Line 1");
CustStreet2Lbl.setText("Street Address Line 2");
CustCityLbl.setText("City");
CustZipLbl.setText("Zip");
CustFindButton.setText("Search");
CustFindButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustFindButtonActionPerformed(evt);
}
});
CustCreateButton.setText("Create/Update");
CustCreateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustCreateButtonActionPerformed(evt);
}
});
custOrdLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
custOrdLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
custOrdLstValueChanged(evt);
}
});
CustOrderListBox.setViewportView(custOrdLst);
CustOrderListBoxLbl.setText("Order(s):");
CustClearButton.setText("Clear Fields");
CustClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustClearButtonActionPerformed(evt);
}
});
CustActiveOrderLbl.setForeground(new java.awt.Color(255, 0, 0));
CustActiveOrderLbl.setText("*Active orders in red");
CUSTIDLbl.setText("Customer Number");
CustStateCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"", "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA",
"ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" }));
CustStateCB.setPreferredSize(new java.awt.Dimension(35, 20));
CustStateCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustStateCBActionPerformed(evt);
}
});
CustStateLbl.setText("State");
InvSearchLbl5.setForeground(new java.awt.Color(255, 51, 51));
InvSearchLbl5.setText("* Use only one field for searches");
CustPhoneLbl.setText("Phone Number");
CustEmailLbl.setText("Email");
javax.swing.GroupLayout CustomerInfoPanelLayout = new javax.swing.GroupLayout(CustomerInfoPanel);
CustomerInfoPanel.setLayout(CustomerInfoPanelLayout);
CustomerInfoPanelLayout.setHorizontalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustEmailLbl)
.addComponent(InvSearchLbl5)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustPhoneLbl)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustStateLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(CustCityLbl)
.addComponent(CustStreet2Lbl)
.addComponent(CustStreet1Lbl)
.addComponent(CustOrgLbl)
.addComponent(CustFNameLbl)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustZipLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CUSTIDLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustActiveOrderLbl)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrderListBoxLbl)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustFindButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustCreateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustClearButton)))
.addContainerGap(286, Short.MAX_VALUE))
);
CustomerInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CustCityText, CustEmailText, CustFNameText, CustLNameText, CustOrgText, CustPhoneText, CustStreet1Text, CustStreet2Text, CustZipText});
CustomerInfoPanelLayout.setVerticalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustOrderListBoxLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustActiveOrderLbl))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CUSTIDLbl)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipLbl)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStateLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustPhoneLbl)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustEmailLbl)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFindButton)
.addComponent(CustCreateButton)
.addComponent(CustClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvSearchLbl5)
.addContainerGap(208, Short.MAX_VALUE))
);
WSCInterface.addTab("Customer Info", CustomerInfoPanel);
OrderNumberLbl.setText("Order Number");
OrderPayTypeBG.add(OrderDeliverPayRB);
OrderDeliverPayRB.setText("Payment on Delivery");
OrderPayTypeBG.add(OrderAccountPayRB);
OrderAccountPayRB.setText("Payment on Account");
OrderDepositLbl.setText("Deposit Amount");
OrderTypeBG.add(OrderTypeShirtRB);
OrderTypeShirtRB.setText("Shirt");
OrderTypeBG.add(OrderTypeTrophyRB);
OrderTypeTrophyRB.setText("Trophy");
OrderTypeBG.add(OrderTypePlaqueRB);
OrderTypePlaqueRB.setText("Plaque");
OrderContentLbl.setText("Printing/Engraving Content:");
OrderMediaCatNumLbl.setText("Media Catalog Number");
OrderMediaTypeLbl.setText("Media Type");
OrderCustNumberLbl.setText("Customer Number");
OrderPaymentTypeLbl.setText("Payment Type");
OrderClearFieldsButton.setText("Clear Fields");
OrderClearFieldsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderClearFieldsButtonActionPerformed(evt);
}
});
OrderCreateBtn.setText("Create");
OrderCreateBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderCreateBtnActionPerformed(evt);
}
});
OrderSearchButton.setText("Search");
OrderSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderSearchButtonActionPerformed(evt);
}
});
OrderMediaStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusLbl.setText("Order Status");
OrderStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderStatusCBActionPerformed(evt);
}
});
OrderMediaStatusLbl.setText("Media Status");
OrderTotalLbl.setText("Estimated Total");
OrderVerifyByLbl.setText("Order Verified by ******");
OrderAssignedToLbl.setText("Work Assigned to ******");
OrderCreatedByLbl.setText("Order Created by ******");
OrderNumberCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderNumberCBActionPerformed(evt);
}
});
OrderSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
OrderSearchLbl.setText("* Use only one field for searches");
OrderUpdateBtn.setText("Update");
javax.swing.GroupLayout OrderInfoPanelLayout = new javax.swing.GroupLayout(OrderInfoPanel);
OrderInfoPanel.setLayout(OrderInfoPanelLayout);
OrderInfoPanelLayout.setHorizontalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderTypeShirtRB)
.addComponent(OrderTypePlaqueRB)
.addComponent(OrderTypeTrophyRB)
.addComponent(OrderStatusLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderAccountPayRB)
.addComponent(OrderDeliverPayRB)
.addComponent(OrderPaymentTypeLbl)
.addComponent(OrderTotalLbl)
.addComponent(OrderMediaTypeLbl)
.addComponent(OrderMediaCatNumLbl)
.addComponent(OrderNumberLbl)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderInfoPanelLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(OrderMediaStatusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderClearFieldsButton)
.addComponent(OrderUpdateBtn)
.addComponent(OrderCreateBtn)
.addComponent(OrderSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(131, Short.MAX_VALUE))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(215, 215, 215)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderVerifyByLbl)
.addComponent(OrderCreatedByLbl))
.addGap(48, 48, 48)
.addComponent(OrderAssignedToLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(OrderDepositLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(371, 371, 371)
.addComponent(OrderSearchLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(331, 331, 331)
.addComponent(OrderContentLbl)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderNumberCB, OrderStatusCB, OrderTotalText});
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderClearFieldsButton, OrderCreateBtn, OrderSearchButton, OrderUpdateBtn});
OrderInfoPanelLayout.setVerticalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumLbl))
.addGap(8, 8, 8)
.addComponent(OrderMediaTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeShirtRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeTrophyRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypePlaqueRB)
.addGap(40, 40, 40)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OrderPaymentTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderAccountPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderDeliverPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositLbl)))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(OrderContentLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(OrderSearchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderCreateBtn)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderUpdateBtn)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusLbl)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderClearFieldsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
.addComponent(OrderSearchLbl)
.addGap(18, 18, 18)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderCreatedByLbl)
.addComponent(OrderAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderVerifyByLbl)
.addGap(51, 51, 51))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderStatusCB, OrderTotalText});
OrderTabbedPane.addTab("Order Info", OrderInfoPanel);
OVSubmitButton.setText("Submit/Assign");
OVSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSubmitButtonActionPerformed(evt);
}
});
OVClearFieldButton.setText("Clear Fields");
OVClearFieldButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVClearFieldButtonActionPerformed(evt);
}
});
OVSearchButton.setText("Search");
OVSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSearchButtonActionPerformed(evt);
}
});
OVCorrectNameLbl.setText("Correct Name");
OVAcctNumLbl.setText("Correct Account Number");
OVMediaNumLbl.setText("Valid Media Cat. #");
OVContentLbl.setText("Valid Content");
OVNameBG.add(OVCorrectNamePassRb);
OVCorrectNamePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNamePassRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumPassRb);
OVAcctNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumPassRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumPassRb);
OVMediaNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumPassRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentPassRb);
OVContentPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentPassRbActionPerformed(evt);
}
});
OVNameBG.add(OVCorrectNameFailRb);
OVCorrectNameFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNameFailRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumFailRb);
OVAcctNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumFailRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumFailRb);
OVMediaNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumFailRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentFailRb);
OVContentFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentFailRbActionPerformed(evt);
}
});
OVCommentsText.setColumns(20);
OVCommentsText.setRows(5);
OVCommentsTB.setViewportView(OVCommentsText);
OVCommentsLbl.setText("Additional Comments");
OVNameFailText.setEditable(false);
OVAcctNumFailText.setEditable(false);
OVMediaFailText.setEditable(false);
OVContentFailText.setEditable(false);
OVPassLbl.setText("Pass");
OVFailLbl.setText("Fail");
OVReasonLbl.setText("Reason for Failure");
OVDepositBG.add(OVDepositPassRb);
OVDepositPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositPassRbActionPerformed(evt);
}
});
OVDepositLbl.setText("Sufficient Deposit");
OVDepositBG.add(OVDepositFailRb);
OVDepositFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositFailRbActionPerformed(evt);
}
});
OVPaymentBG.add(OVPayTypeFailRb);
OVPayTypeFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypeFailRbActionPerformed(evt);
}
});
OVPayTypePassLbl.setText("Payment Type");
OVDepositFailText.setEditable(false);
OVPayTypeFailText.setEditable(false);
OVPaymentBG.add(OVPayTypePassRb);
OVPayTypePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypePassRbActionPerformed(evt);
}
});
OVNumberLbl.setText("Verification Number");
OVContentValLbl.setToolTipText("");
OVContentValLbl.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
OVContentValLblMouseClick(evt);
}
});
OVAssignEmpCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OVAssignEmpLbl.setText("Assign Printer/Engraver");
OVOrderNumLbl.setText("Order Number");
OVVerifyByLbl.setText("Order Verified by ******");
OVCreateByLbl.setText("Order Created by ******");
OVAssignedToLbl.setText("Work Assigned to ******");
OVButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
javax.swing.GroupLayout OrderVerifyPanelLayout = new javax.swing.GroupLayout(OrderVerifyPanel);
OrderVerifyPanel.setLayout(OrderVerifyPanelLayout);
OrderVerifyPanelLayout.setHorizontalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVNumberLbl)
.addComponent(OVOrderNumLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVCorrectNameLbl)
.addComponent(OVAcctNumLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVContentLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVDepositLbl))
.addGap(15, 15, 15)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositPassRb)
.addComponent(OVPayTypePassRb)
.addComponent(OVContentPassRb)
.addComponent(OVMediaNumPassRb)
.addComponent(OVAcctNumPassRb)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVPassLbl))
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositFailRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVContentFailRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVFailLbl))
.addComponent(OVMediaNumFailRb, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVNameFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVReasonLbl))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVButtonLbl)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVVerifyByLbl)
.addComponent(OVCreateByLbl))
.addGap(48, 48, 48)
.addComponent(OVAssignedToLbl))
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OVAssignEmpLbl))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVDepositValLbl)
.addComponent(OVPayTypeValLbl)
.addComponent(OVContentValLbl)
.addComponent(OVMediaCatValLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVCustNameValLbl)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVSubmitButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVClearFieldButton)))
.addGap(373, 419, Short.MAX_VALUE))))
);
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVAcctNumFailText, OVContentFailText, OVMediaFailText, OVNameFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVDepositFailText, OVPayTypeFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVOrderIDText, OVerIDText});
OrderVerifyPanelLayout.setVerticalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVOrderNumLbl)
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVNumberLbl)
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVPassLbl)
.addComponent(OVFailLbl)
.addComponent(OVReasonLbl)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVCustNameValLbl)
.addComponent(OVCorrectNameLbl)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVNameFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVAcctNumLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVAcctNumPassRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVMediaCatValLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVMediaNumPassRb)
.addComponent(OVMediaNumFailRb)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVContentValLbl)
.addComponent(OVContentLbl)
.addComponent(OVContentPassRb)
.addComponent(OVContentFailRb)
.addComponent(OVContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVPayTypeValLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVPayTypePassRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositValLbl)
.addComponent(OVDepositLbl)
.addComponent(OVDepositPassRb)
.addComponent(OVDepositFailRb)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVAssignEmpLbl)
.addComponent(OVCommentsLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVSearchButton)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVClearFieldButton)
.addComponent(OVSubmitButton))))
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addComponent(OVButtonLbl)
.addGap(1, 1, 1)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVCreateByLbl)
.addComponent(OVAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVVerifyByLbl)
.addContainerGap(176, Short.MAX_VALUE))
);
OrderTabbedPane.addTab("Order Verify", OrderVerifyPanel);
QASubmitButton.setText("Submit");
QASubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASubmitButtonActionPerformed(evt);
}
});
QAClearButton.setText("Clear Fields");
QAClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAClearButtonActionPerformed(evt);
}
});
QASearchButton.setText("Search");
QASearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASearchButtonActionPerformed(evt);
}
});
QAContentLbl.setText("Correct Order Content");
QAMediaLbl.setText("Correct Order Media");
QAMediaFinishLbl.setText("Media Finish");
QAWorkmanshipLbl.setText("Workmanship");
QAContentBG.add(QAContentCheckPassRb);
QAContentCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckPassRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckPassRb);
QAMediaCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckPassRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckPassRb);
QAMediaFinishCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckPassRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckPassRb);
QAWorkmanshipCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckPassRbActionPerformed(evt);
}
});
QAContentBG.add(QAContentCheckFailRb);
QAContentCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckFailRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckFailRb);
QAMediaCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckFailRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckFailRb);
QAMediaFinishCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckFailRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckFailRb);
QAWorkmanshipCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckFailRbActionPerformed(evt);
}
});
QACorrectiveActionText.setColumns(20);
QACorrectiveActionText.setRows(5);
QACorrectiveActionTB.setViewportView(QACorrectiveActionText);
QACommentLbl.setText("Comments");
QAPassLbl.setText("Pass");
QAFailLbl.setText("Fail");
QAFailCommentLbl.setText("Reason for Failure");
QAVerifiedByLbl.setText("Order Verified by ******");
QACreatedByLbl.setText("Order Created by ******");
QAAssignedToLbl.setText("Work Assigned to ******");
QAOrderIDLbl.setText("Order Number");
QAIDLbl.setText("QA Inspection Number");
QAButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
QAButtonLbl.setText("* Use only one field for searches");
javax.swing.GroupLayout QAPanelLayout = new javax.swing.GroupLayout(QAPanel);
QAPanel.setLayout(QAPanelLayout);
QAPanelLayout.setHorizontalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAOrderIDLbl)
.addComponent(QAIDLbl))
.addGap(23, 23, 23)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAVerifiedByLbl)
.addComponent(QACreatedByLbl))
.addGap(48, 48, 48)
.addComponent(QAAssignedToLbl))
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAMediaLbl)
.addComponent(QAMediaFinishLbl)
.addComponent(QAWorkmanshipLbl)
.addComponent(QAContentLbl))
.addGap(17, 17, 17)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAPassLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentCheckFailRb)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAFailLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAFailCommentLbl)))
.addComponent(QACommentLbl)
.addGroup(QAPanelLayout.createSequentialGroup()
.addComponent(QASearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QASubmitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAClearButton))
.addComponent(QAOrderIDText, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
.addComponent(QAIDText)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)))
.addContainerGap(197, Short.MAX_VALUE))
);
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAContentFailText, QAMediaFailText, QAMediaFinishFailText, QAWorkmanshipFailText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAIDText, QAOrderIDText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAClearButton, QASearchButton, QASubmitButton});
QAPanelLayout.setVerticalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAOrderIDLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAIDLbl))
.addGap(24, 24, 24)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QAPassLbl)
.addComponent(QAFailLbl)
.addComponent(QAFailCommentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentCheckFailRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAContentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAMediaLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAMediaFinishLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAWorkmanshipLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addComponent(QACommentLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QASearchButton)
.addComponent(QASubmitButton)
.addComponent(QAClearButton))
.addGap(2, 2, 2)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QACreatedByLbl)
.addComponent(QAAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAVerifiedByLbl)
.addGap(88, 88, 88))
);
OrderTabbedPane.addTab("Quality Assurance", QAPanel);
WSCInterface.addTab("Order", OrderTabbedPane);
InvItemIDLbl.setText("Item Number");
InvManufacturerIdLbl.setText("Manufacturer");
InvQtyOnHandLbl.setText("On Hand");
InvQtyOnOrderLbl.setText("On Order");
InvDeliveryDateLbl.setText("Delivery Date");
InvOrderButton.setText("Order/Mark Sold");
InvOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvOrderButtonActionPerformed(evt);
}
});
InvClearButton.setText("Clear Fields");
InvClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvClearButtonActionPerformed(evt);
}
});
InvSearchButton.setText("Search");
InvSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvSearchButtonActionPerformed(evt);
}
});
InvItemNameLbl.setText("Item Name");
InvButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
InvButtonLbl.setText("* Use only one field for searches");
InvOrderIdLbl.setText("Order");
InvManufacturerItemList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
InvManufacturerItemScrollPane.setViewportView(InvManufacturerItemList);
InvManufacturerItemLbl.setText("Items:");
javax.swing.GroupLayout InventoryPanelLayout = new javax.swing.GroupLayout(InventoryPanel);
InventoryPanel.setLayout(InventoryPanelLayout);
InventoryPanelLayout.setHorizontalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(137, 137, 137)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvDeliveryDateLbl)
.addComponent(InvQtyOnOrderLbl)
.addComponent(InvQtyOnHandLbl)
.addComponent(InvItemNameLbl)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvItemIDLbl)
.addComponent(InvSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvOrderIdLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOrderButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(InvOnOrderText)
.addComponent(InvOnHandText)
.addComponent(InvItemNameText)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvItemIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvClearButton))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvManufacturerItemLbl)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(InvButtonLbl))
.addContainerGap(294, Short.MAX_VALUE))
);
InventoryPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {InvClearButton, InvDeliveryDateText, InvItemIdText, InvItemNameText, InvManufacturerIdText, InvOnHandText, InvOnOrderText, InvOrderButton, InvOrderIdText, InvSearchButton});
InventoryPanelLayout.setVerticalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(93, 93, 93)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvOrderIdLbl)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvItemIDLbl)
.addComponent(InvItemIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvItemNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvItemNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnHandText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnHandLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnOrderText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnOrderLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvDeliveryDateLbl)))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(InvManufacturerItemLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvSearchButton)
.addComponent(InvOrderButton)
.addComponent(InvClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvButtonLbl)
.addContainerGap(307, Short.MAX_VALUE))
);
WSCInterface.addTab("Inventory", InventoryPanel);
EmpFNameLbl.setText("First Name");
EmpLNameLbl.setText("Last Name");
EmpSearchButton.setText("Search");
EmpSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSearchButtonActionPerformed(evt);
}
});
EmpSubmitButton.setText("Create/Update");
EmpSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSubmitButtonActionPerformed(evt);
}
});
emOrdersLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
emOrdersLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
emOrdersLstValueChanged(evt);
}
});
EmpOrderLB.setViewportView(emOrdersLst);
EmpOrderLbl.setText("Order(s):");
EmpClearButton.setText("Clear Fields");
EmpClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpClearButtonActionPerformed(evt);
}
});
EmpActiveOrderLbl1.setForeground(new java.awt.Color(255, 0, 0));
EmpActiveOrderLbl1.setText("*Active orders in red");
EMPIDLbl.setText("Employee id");
EmpTypeCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TS", "Item 1", "Item 2", "Item 3", "Item 4" }));
EmpTypeCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpTypeCBActionPerformed(evt);
}
});
EmpTypeLbl.setText("Employee Type");
EmpSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
EmpSearchLbl.setText("* Use only one field for searches");
jLabel1.setText("Email Address");
jLabel3.setText("Login Password");
jLabel4.setText("Confirm Password");
javax.swing.GroupLayout EmployeeInfoPanelLayout = new javax.swing.GroupLayout(EmployeeInfoPanel);
EmployeeInfoPanel.setLayout(EmployeeInfoPanelLayout);
EmployeeInfoPanelLayout.setHorizontalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(135, 135, 135)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(EmpTypeLbl)
.addComponent(jLabel1)
.addComponent(EmpLNameLbl)
.addComponent(EmpFNameLbl)
.addComponent(EMPIDLbl))
.addGap(27, 27, 27)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(EmpActiveOrderLbl1))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EmpOrderLbl)
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EmpSearchLbl)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addComponent(EmpSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EmpSubmitButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpClearButton)))
.addContainerGap(241, Short.MAX_VALUE))
);
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDCB, EmpClearButton, EmpEmail, EmpFNameText, EmpLNameText, EmpPass, EmpPassConfirm, EmpSubmitButton, EmpTypeCB});
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDLbl, EmpFNameLbl, EmpLNameLbl, EmpSearchButton, EmpTypeLbl, jLabel1, jLabel3, jLabel4});
EmployeeInfoPanelLayout.setVerticalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(EmpOrderLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EMPIDLbl)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpFNameLbl)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel1)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmpSubmitButton)
.addComponent(EmpClearButton)
.addComponent(EmpSearchButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpSearchLbl))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(EmpActiveOrderLbl1)))
.addContainerGap(217, Short.MAX_VALUE))
);
WSCInterface.addTab("Employee Info", EmployeeInfoPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 789, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("");
}// </editor-fold>//GEN-END:initComponents
/* Brad Clawson: These class objects are created to represent the global objects
* that are passed between the tabs in the GUI -
*/
private Employee login = new Employee();
private Customer workingCustomer = new Customer();
private Order workingOrder = new Order();
private OrderVerify workingOV = null;
private QAReport workingQA = new QAReport();
private InventoryItem workingII = new InventoryItem();
public void HideEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Hide password employee fields by default">
EmpPass.setVisible(false);
EmpPassConfirm.setVisible(false);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
// </editor-fold>
}
public void ShowEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Show password employee fields by default">
EmpPass.setVisible(true);
EmpPassConfirm.setVisible(true);
jLabel3.setVisible(true);
jLabel4.setVisible(true);
// </editor-fold>
}
private void setOrderNumberCBModel(ArrayList<Order> orders) {
this.OrderNumberCB.removeAllItems();
for (Order o : orders) {
this.OrderNumberCB.addItem(o);
}
}
private void populateOrderTab(Order order) {
// Media Type Radio Buttons
if (order.getMediaType() != null) {
switch (order.getMediaType().toLowerCase()) {
case "trophy":
this.OrderTypeTrophyRB.setSelected(true);
break;
case "plaque":
this.OrderTypePlaqueRB.setSelected(true);
break;
case "shirt":
this.OrderTypeShirtRB.setSelected(true);
break;
default:
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
}
}
// Set OrderTotalText
this.OrderTotalText.setText(String.format("%.2f", order.getTotal()));
// Set OrderDepositText
this.OrderDepositText.setText(String.format("%.2f", order.getDeposit()));
// Set Accout Payment Radio button
if (order.getPaymentOnAccount())
this.OrderAccountPayRB.setSelected(true);
else if (!order.getPaymentOnAccount())
this.OrderDeliverPayRB.setSelected(true);
// Set Order Status CB
this.OrderStatusCB.removeAllItems();
for (Order.OrderStatus os : Order.OrderStatus.values())
this.OrderStatusCB.addItem(os.toString());
this.OrderStatusCB.setSelectedItem(order.getOrderStatus());
// Set the MediaStatusCB
this.OrderMediaStatusCB.removeAllItems();
for (Order.MediaStatus ms : Order.MediaStatus.values())
this.OrderMediaStatusCB.addItem(order.getMediaStatus());
this.OrderMediaStatusCB.setSelectedItem(order.getMediaStatus());
// Set Content Text
this.OrderContentText.setText(order.getContent());
this.OrderContentText.setEditable(true);
}
private void selectOrderByIndex(int index) {
Order order = (Order)this.OrderNumberCB.getItemAt(index);
this.populateOrderTab(order);
}
private void CustStateCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustStateCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_CustStateCBActionPerformed
private void CustClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustClearButtonActionPerformed
//Clear all fields on customer info
CustClear();
}//GEN-LAST:event_CustClearButtonActionPerformed
public void CustClear() {
//Jacob: Created clear method as it will need called once the customer is created.
CUSTIDCB.setText("");
CustFNameText.setText("");
CustLNameText.setText("");
CustOrgText.setText("");
CustStreet1Text.setText("");
CustStreet2Text.setText("");
CustCityText.setText("");
CustZipText.setText("");
CustPhoneText.setText("");
CustEmailText.setText("");
CustStateCB.setSelectedIndex(0);
custOrdLst.setListData(new Object[0]);
}
private void CustCreateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustCreateButtonActionPerformed
//Jacob: Added Try and Catch to check if parse was successful
//if not through a message explaining
boolean CustExist = false;
String temp;
try{
//Get address and assign an empty string if it doesnt exist
if ("".equals(CustStreet1Text.getText()))
{
temp = "";
}
else
{
temp = CustStreet1Text.getText();
}
//Check if customer exists
CustExist = Customer.isCustomer(Integer.parseInt(CUSTIDCB.getText()),temp);
//If the customer doesnt exist create them else cust already exists update
if (CustExist == false)
{
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.createCust(customer);
JOptionPane.showMessageDialog(null, "Customer created successfully.");
// CustClear();
}
else
{
//Update the customer
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.updateBy(customer);
JOptionPane.showMessageDialog(null, "Customer updated.");
// CustClear();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "A numeric value is required for the following:\nCustomer ID\nCustomer Zip\nCustomer Phone Number", "Numeric Value Required", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Customer was not created.");
}
}//GEN-LAST:event_CustCreateButtonActionPerformed
private void CustFindButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustFindButtonActionPerformed
Customer searchCust = null;
ArrayList<String> cust = new ArrayList<String>();
//Search input to specify column to seach
// <editor-fold defaultstate="collapsed" desc="Get Query for cust search">
if (!"".equals(CUSTIDCB.getText()))
{
searchCust = Customer.searchBy("CUSTID", CUSTIDCB.getText());
}
if (!"".equals(CustFNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustFirstName", CustFNameText.getText());
}
if (!"".equals(CustLNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustLastName", CustLNameText.getText());
}
if (!"".equals(CustOrgText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustOrg", CustOrgText.getText());
}
if (!"".equals(CustStreet1Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet1", CustStreet1Text.getText());
}
if (!"".equals(CustStreet2Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet2", CustStreet2Text.getText());
}
if (!"".equals(CustPhoneText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustPhone", CustPhoneText.getText());
}
//Check if searchCust is null, if not set the customer information
if (searchCust == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
// <editor-fold defaultstate="collapsed" desc="Set customer data to tab">
CUSTIDCB.setText(String.valueOf(searchCust.getCustId()));
CustFNameText.setText(searchCust.getCustFName());
CustLNameText.setText(searchCust.getCustLName());
CustStreet1Text.setText(searchCust.getCustStreet1());
CustStreet2Text.setText(searchCust.getCustStreet2());
CustCityText.setText(searchCust.getCustCity());
CustZipText.setText(String.valueOf(searchCust.getCustZip()));
CustPhoneText.setText(String.valueOf(searchCust.getCustPhone()));
CustEmailText.setText(searchCust.getCustEmail());
CustStateCB.setSelectedItem(searchCust.getCustState());
CustOrgText.setText(searchCust.getCustOrg());
cust = Customer.getOrders(Long.parseLong(CUSTIDCB.getText()));
custOrdLst.setListData(cust.toArray());
// </editor-fold>
}
// </editor-fold>
}//GEN-LAST:event_CustFindButtonActionPerformed
private void LoginPassTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginPassTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginPassTextActionPerformed
private void LoginEMPIDTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginEMPIDTxtActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginEMPIDTxtActionPerformed
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
Login.processLogin(LoginEMPIDTxt.getText(), LoginPassText.getText());
// SetAccessLevel();
}//GEN-LAST:event_LoginButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA Search,Submit,Clear Buttons">
private void QASubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* QAReport object to QAReport.insertOrUpdateQA() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the QAIDText field
* to populate the screen with the information that is searched for and
* verified by the popQA() method. If popQA() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean contentCheck = false, mediaCheck = false, mediaFinishCheck = false,
workmanshipCheck = false, depositCheck = false;
String contentComment = "", mediaComment = "", mediaFinishComment = "",
workmanshipComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if QA check fails
if(QAContentCheckPassRb.isSelected()){
contentCheck = Boolean.TRUE;
}
else if(QAContentCheckFailRb.isSelected()){
contentCheck = Boolean.FALSE;
contentComment = QAContentFailText.getText();
}
if(QAMediaCheckPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(QAMediaCheckFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = QAMediaFailText.getText();
}
if(QAMediaFinishCheckPassRb.isSelected()){
mediaFinishCheck = Boolean.TRUE;
}
else if(QAMediaFinishCheckFailRb.isSelected()){
mediaFinishCheck = Boolean.FALSE;
mediaFinishComment = QAMediaFailText.getText();
}
if(QAWorkmanshipCheckPassRb.isSelected()){
workmanshipCheck = (Boolean.TRUE);
}
else if(QAWorkmanshipCheckFailRb.isSelected()){
workmanshipCheck = (Boolean.FALSE);
workmanshipComment = (QAWorkmanshipFailText.getText());
}
if(QAContentCheckFailRb.isSelected()||
QAMediaCheckFailRb.isSelected()||
QAMediaFinishCheckFailRb.isSelected()||
QAWorkmanshipCheckFailRb.isSelected()){
correctiveActionComment = (QACorrectiveActionText.getText());
}
//Create new QAReport object with screen data to be passed to insertOrUpdateQA()
QAReport newQA = new QAReport((Integer.parseInt(QAIDText.getText())),
Order.getOrder(Integer.parseInt(QAOrderIDText.getText())),
Login.emp, contentCheck, mediaCheck, mediaFinishCheck,
workmanshipCheck, contentComment, mediaComment, mediaFinishComment,
workmanshipComment, correctiveActionComment);
//Object that is returned verifies that the object was created
newQA = QAReport.insertOrUpdateQA(newQA);
//prepare the screen for popQA;
QAIDText.setText(String.valueOf(newQA.getQAID()));
QAOrderIDText.setText("");
//Object is verified a second time through popQA and QAbuttonLbl informs results
if(popQA()){
QAButtonLbl.setText("Create/Update Successful");}
else {
QAButtonLbl.setText("Create/Update Unsuccessful");
}
}//GEN-LAST:event_QASubmitButtonActionPerformed
private void QAClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAClearButtonActionPerformed
//Brad Clawson: Clear information entered into QA tab
QAIDText.setText("");
QAOrderIDText.setText("");
QAContentFailText.setText("");
QAMediaFailText.setText("");
QAMediaFinishFailText.setText("");
QAWorkmanshipFailText.setText("");
QACorrectiveActionText.setText("");
QAContentBG.clearSelection();
QAMediaBG.clearSelection();
QAMediaFinishBG.clearSelection();
QAWorkmanshipBG.clearSelection();
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}//GEN-LAST:event_QAClearButtonActionPerformed
private void QASearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASearchButtonActionPerformed
//Brad Clawson: This method calls the popQA() method to populate the tab
if(popQA()){
QAButtonLbl.setText("Record Found");
}
else{
QAButtonLbl.setText(QAButtonLbl.getText() + ".\n"+"Record Not Found");
}
}//GEN-LAST:event_QASearchButtonActionPerformed
private Boolean popQA(){
/*
* Brad Clawson: Populates Quality Assurance tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND QAID is null or empty search by OrderID
if ((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("ORDERID", Integer.parseInt(QAOrderIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF QAID is not null or empty AND OrderID is null or empty search by QAID
else if ((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("QAID", Integer.parseInt(QAIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF OrderID and QAID are null or empty, notify user to enter proper search criteria
else if((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Please enter a search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//IF OrderID and QAID both not null or empty, notify user to enter single search criteria
else if((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Use a single search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//fill tab content with values from QAReport that was returned in search
QAOrderIDText.setText(String.valueOf(workingQA.getOrder().getORDID()));
QAIDText.setText(String.valueOf(workingQA.getQAID()));
//select correct radio boxes and set fail comments editable or ineditable
if(workingQA.getContentCheck()){
QAContentCheckPassRb.setSelected(true);
QAContentFailText.setEditable(false);}
else if(!workingQA.getContentCheck()){
QAContentCheckFailRb.setSelected(true);
QAContentFailText.setText(workingQA.getContentFailComment());
QAContentFailText.setEditable(true);}
if(workingQA.getMediaCheck()){
QAMediaCheckPassRb.setSelected(true);
QAMediaFailText.setEditable(false);}
else if(!workingQA.getMediaCheck()){
QAMediaCheckFailRb.setSelected(true);
QAMediaFailText.setText(workingQA.getMediaFailComment());
QAMediaFailText.setEditable(true);}
if(workingQA.getMediaFinishCheck()){
QAMediaFinishCheckPassRb.setSelected(true);
QAMediaFinishFailText.setEditable(false);}
else if(!workingQA.getMediaFinishCheck()){
QAMediaFinishCheckFailRb.setSelected(true);
QAMediaFinishFailText.setText(workingQA.getMediaFinishFailComment());
QAMediaFinishFailText.setEditable(true);}
if(workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckPassRb.setSelected(true);
QAWorkmanshipFailText.setEditable(false);}
else if(!workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckFailRb.setSelected(true);
QAWorkmanshipFailText.setText(workingQA.getWorkmanshipFailComment());
QAWorkmanshipFailText.setEditable(true);}
//page successfully populated return true to indicate success
return true;
}
private void QAOrderIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad:reset background color if changed from invalid search param
QAOrderIDText.setBackground(Color.white);
}
private void QAIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad: reset background color if changed from invalid search param
QAIDText.setBackground(Color.white);
}
//</editor-fold>
private void OrderClearFieldsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderClearFieldsButtonActionPerformed
this.OrderCUSTIDText.setText("");
this.OrderNumberCB.removeAllItems();
this.OrderMediaCatNumText.setText("");
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTotalText.setText("");
this.OrderAccountPayRB.setSelected(false);
this.OrderDeliverPayRB.setSelected(false);
this.OrderDepositText.setText("");
this.OrderStatusCB.setSelectedIndex(0);
this.OrderMediaStatusCB.setSelectedIndex(0);
this.OrderContentText.setText("");
}//GEN-LAST:event_OrderClearFieldsButtonActionPerformed
private void OrderCreateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderCreateBtnActionPerformed
Customer cust = Customer.searchBy("CUSTID", "1");
String content = this.OrderContentText.getText();
boolean onAcct = false;
String mediaType = "";
if (this.OrderTypePlaqueRB.isSelected())
mediaType = "plaque";
else if (this.OrderTypeShirtRB.isSelected())
mediaType = "shirt";
else if (this.OrderTypeTrophyRB.isSelected())
mediaType = "trophy";
if (this.OrderAccountPayRB.isSelected())
onAcct = true;
float total = Float.parseFloat(this.OrderTotalText.getText());
float deposit = Float.parseFloat(this.OrderDepositText.getText());
String orderStatus = (String)this.OrderStatusCB.getSelectedItem();
String mediaStatus = (String)this.OrderMediaStatusCB.getSelectedItem();
Employee employee;
if (Login.emp != null)
employee = Login.emp;
else
employee = Employee.searchBy(1);
// Create new Order obj
Order order = new Order(cust, 0, mediaType, content, onAcct, total, deposit, orderStatus, mediaStatus, employee);
order = Order.createOrder(order); // Put into DB
this.populateOrderTab(order); // Populate view from the created obj (see errors this way)
}//GEN-LAST:event_OrderCreateBtnActionPerformed
private void OrderSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderSearchButtonActionPerformed
if (this.OrderCUSTIDText.getText().length() > 0) {
this.orders = Order.getOrders(Integer.parseInt(this.OrderCUSTIDText.getText()));
this.setOrderNumberCBModel(orders);
this.selectOrderByIndex(0);
}
else {
JOptionPane.showMessageDialog(null, "Please search by Customer ID", "Error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_OrderSearchButtonActionPerformed
private void LogoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutButtonActionPerformed
Login.processLogout();
/* //Brad: make all tabs except login invisible Login action will set user access
CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/
}//GEN-LAST:event_LogoutButtonActionPerformed
private void EmpSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSearchButtonActionPerformed
// TODO add your handling code here:
Employee emp = null;
ArrayList<String> orders = new ArrayList<String>();
if (!"".equals(EMPIDCB.getText()))
{
emp = Employee.searchBy(Long.parseLong(EMPIDCB.getText()));
orders = Employee.getOrders(Long.parseLong(EMPIDCB.getText()));
emOrdersLst.setListData(orders.toArray());
}
if (emp == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
EMPIDCB.setText(String.valueOf(emp.getEmpId()));
EmpFNameText.setText(emp.getFirstName());
EmpLNameText.setText(emp.getLastName());
EmpEmail.setText(emp.getEmail());
EmpTypeCB.setSelectedItem(emp.getEmpType());
ShowEmpPassword();
}
}//GEN-LAST:event_EmpSearchButtonActionPerformed
private void EmpSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSubmitButtonActionPerformed
boolean empExist = false;
boolean empUser = false;
String temp;
try{
//Check if employee exists
empExist = Employee.isEmployee(Long.parseLong(EMPIDCB.getText()));
//If the employee doesn't exist create them else employee already exists update
if (empExist == false)
{
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.createEmp(emp);
JOptionPane.showMessageDialog(null, "Employee created successfully.");
//EmpClear();
HideEmpPassword();
}
else
{
String passText = new String(EmpPass.getPassword());
String passTextConfirm = new String(EmpPassConfirm.getPassword());
if (!passText.equals(passTextConfirm))
{
JOptionPane.showMessageDialog(null, "Employee password does not match.");
}
else
{
//Update the employee
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateBy(emp);
emp = null;
empUser = Employee.empUserExist(Long.parseLong(EMPIDCB.getText()));
if (empUser == false)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.addUserLogin(emp);
}
if (empUser == true)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateUserLogin(emp);
}
JOptionPane.showMessageDialog(null, "Employee updated.");
//EmpClear();
HideEmpPassword();
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Employee was not created.");
}
}//GEN-LAST:event_EmpSubmitButtonActionPerformed
public void EmpClear(){
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpTypeCB.setSelectedIndex(0);
}
private void EmpClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpClearButtonActionPerformed
// Clear Employee data
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpPass.setText("");
EmpPassConfirm.setText("");
EmpTypeCB.setSelectedIndex(0);
emOrdersLst.setListData(new Object[0]);
}//GEN-LAST:event_EmpClearButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA radio buttons">
private void QAContentCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAContentFailText.setEditable(false);
}//GEN-LAST:event_QAContentCheckPassRbActionPerformed
private void QAMediaCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFailText.setEditable(false);
}//GEN-LAST:event_QAMediaCheckPassRbActionPerformed
private void QAMediaFinishCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFinishFailText.setEditable(false);
}//GEN-LAST:event_QAMediaFinishCheckPassRbActionPerformed
private void QAWorkmanshipCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAWorkmanshipFailText.setEditable(false);
}//GEN-LAST:event_QAWorkmanshipCheckPassRbActionPerformed
private void QAContentCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAContentFailText.setEditable(true);
}//GEN-LAST:event_QAContentCheckFailRbActionPerformed
private void QAMediaCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFailText.setEditable(true);
}//GEN-LAST:event_QAMediaCheckFailRbActionPerformed
private void QAMediaFinishCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFinishFailText.setEditable(true);
}//GEN-LAST:event_QAMediaFinishCheckFailRbActionPerformed
private void QAWorkmanshipCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAWorkmanshipFailText.setEditable(true);
}//GEN-LAST:event_QAWorkmanshipCheckFailRbActionPerformed
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: OV radio buttons">
private void OVPayTypePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVPayTypePassRb.isSelected()){
OVPayTypeFailText.setEditable(false);
}
}//GEN-LAST:event_OVPayTypePassRbActionPerformed
private void OVPayTypeFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypeFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVPayTypeFailRb.isSelected()){
OVPayTypeFailText.setEditable(true);
}
}//GEN-LAST:event_OVPayTypeFailRbActionPerformed
private void OVDepositFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVDepositFailRb.isSelected()){
OVDepositFailText.setEditable(true);
}
}//GEN-LAST:event_OVDepositFailRbActionPerformed
private void OVDepositPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVDepositPassRb.isSelected()){
OVDepositFailText.setEditable(false);
}
}//GEN-LAST:event_OVDepositPassRbActionPerformed
private void OVContentFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVContentFailRb.isSelected()){
OVContentFailText.setEditable(true);
}
}//GEN-LAST:event_OVContentFailRbActionPerformed
private void OVMediaNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVMediaNumFailRb.isSelected()){
OVMediaFailText.setEditable(true);
}
}//GEN-LAST:event_OVMediaNumFailRbActionPerformed
private void OVAcctNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVAcctNumFailRb.isSelected()){
OVAcctNumFailText.setEditable(true);
}
}//GEN-LAST:event_OVAcctNumFailRbActionPerformed
private void OVCorrectNameFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNameFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVCorrectNameFailRb.isSelected()){
OVNameFailText.setEditable(true);
}
}//GEN-LAST:event_OVCorrectNameFailRbActionPerformed
private void OVContentPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVContentPassRb.isSelected()){
OVContentFailText.setEditable(false);
}
}//GEN-LAST:event_OVContentPassRbActionPerformed
private void OVMediaNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVMediaNumPassRb.isSelected()){
OVMediaFailText.setEditable(false);
}
}//GEN-LAST:event_OVMediaNumPassRbActionPerformed
private void OVAcctNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVAcctNumPassRb.isSelected()){
OVAcctNumFailText.setEditable(false);
}
}//GEN-LAST:event_OVAcctNumPassRbActionPerformed
private void OVCorrectNamePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNamePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVCorrectNamePassRb.isSelected()){
OVNameFailText.setEditable(false);
}
}//GEN-LAST:event_OVCorrectNamePassRbActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Brad Clawson: OV Search,Submit,Clear Buttons">
private void OVSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSearchButtonActionPerformed
//Brad Clawson: search by OVID or OrderID through popID() and indicate success or failure
if(popOV()){
OVButtonLbl.setText("Record Found");
}
else{
OVButtonLbl.setText(OVButtonLbl.getText()+ ". Record not Found");
}
}//GEN-LAST:event_OVSearchButtonActionPerformed
private Boolean popOV(){
/*
* Brad Clawson: Populates Order Verify tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND OVID is null or empty search by OrderID
if ((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("ORDERID", Integer.parseInt(OVOrderIDText.getText()));
}
//IF OVID is not null or empty AND OrderID is null or empty search by OVID
else if ((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("VERID", Integer.parseInt(OVerIDText.getText()));
}
//If both OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Please enter a Order ID or Verification ID for Search");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
//If neither OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Use Only One Field for Searches");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
// make Order information available for easy evaluation
OVCustNameValLbl.setVisible(true);
OVCustIDValLbl.setVisible(true);
OVMediaCatValLbl.setVisible(true);
OVContentValLbl.setVisible(true);
OVPayTypeValLbl.setVisible(true);
OVDepositValLbl.setVisible(true);
OVOrderIDText.setText(String.valueOf(workingOV.getOrder().getORDID()));
- OVerIDText.setText(String.valueOf(workingOV.getVerId()));
+ OVerIDText.setText(String.valueOf(workingOV.getVerID()));
OVCustNameValLbl.setText(workingOV.getOrder().getCustomer().getCustFName()
+ " " + workingOV.getOrder().getCustomer().getCustLName());
OVCustIDValLbl.setText(String.valueOf(workingOV.getOrder().getCustomer().getCustId()));
// OVMedCatValLbl.setText(String.valueOf(workingOV.getOrder().getMedia().getItemID));
OVContentValLbl.setText("(Content)");
OVContentValLbl.setForeground(Color.BLUE);
//set screen values for returned OrderVerify object
if (workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Account");
}
if (!workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Delivery");
}
OVDepositValLbl.setText(String.valueOf(workingOV.getOrder().getDeposit()));
// OVAssignEmpCB
//set radio button values and set fail comments editable or ineditable
if(workingOV.getNameCheck()){
OVCorrectNamePassRb.setSelected(true);
OVNameFailText.setEditable(false);}
else if(!workingOV.getNameCheck()){
OVCorrectNameFailRb.setSelected(true);
OVNameFailText.setText(workingOV.getNameFailComment());
OVNameFailText.setEditable(true);}
if(workingOV.getAccountCheck()){
OVAcctNumPassRb.setSelected(true);
OVAcctNumFailText.setEditable(false);}
else if(!workingOV.getAccountCheck()){
OVAcctNumFailRb.setSelected(true);
OVAcctNumFailText.setText(workingOV.getAccountFailComment());
OVAcctNumFailText.setEditable(true);}
if(workingOV.getMediaCheck()){
OVMediaNumPassRb.setSelected(true);
OVMediaFailText.setEditable(false);}
else if(!workingOV.getMediaCheck()){
OVMediaNumFailRb.setSelected(true);
OVMediaFailText.setText(workingOV.getMediaFailComment());
OVMediaFailText.setEditable(true);}
if(workingOV.getContentCheck()){
OVContentPassRb.setSelected(true);
OVContentFailText.setEditable(false);}
else if(!workingOV.getContentCheck()){
OVContentFailRb.setSelected(true);
OVContentFailText.setText(workingOV.getContentFailComment());
OVContentFailText.setEditable(true);}
if(workingOV.getPaymentCheck()){
OVPayTypePassRb.setSelected(true);
OVPayTypeFailText.setEditable(false);}
else if(!workingOV.getPaymentCheck()){
OVPayTypeFailRb.setSelected(true);
OVPayTypeFailText.setText(workingOV.getPaymentFailComment());
OVPayTypeFailText.setEditable(true);}
if(workingOV.getDepositCheck()){
OVDepositPassRb.setSelected(true);
OVDepositFailText.setEditable(false);}
else if(!workingOV.getDepositCheck()){
OVDepositFailRb.setSelected(true);
OVDepositFailText.setText(workingOV.getDepositFailComment());
OVDepositFailText.setEditable(true);}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected())
{
OVCommentsText.setText(workingOV.getCorrectiveActionComment());
OVCommentsText.setEditable(true);
}
//tab items successfully populated, return true for success
return true;
}
private void OVClearFieldButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVClearFieldButtonActionPerformed
//Brad Clawson: reset all values on OV tab
OVCustNameValLbl.setText("");
OVCustIDValLbl.setText("");
OVMediaCatValLbl.setText("");
OVContentValLbl.setText("");
OVPayTypeValLbl.setText("");
OVDepositValLbl.setText("");
// OVAssignEmpCB.setText("");
OVOrderIDText.setText("");
OVerIDText.setText("");
OVNameBG.clearSelection();
OVAccountBG.clearSelection();
OVPaymentBG.clearSelection();
OVDepositBG.clearSelection();
OVContentBG.clearSelection();
OVMediaBG.clearSelection();
OVNameFailText.setText("");
OVAcctNumFailText.setText("");
OVMediaFailText.setText("");
OVContentFailText.setText("");
OVPayTypeFailText.setText("");
OVDepositFailText.setText("");
OVCommentsText.setText("");
OVCustNameValLbl.setVisible(false);
OVCustIDValLbl.setVisible(false);
OVMediaCatValLbl.setVisible(false);
OVContentValLbl.setVisible(false);
OVPayTypeValLbl.setVisible(false);
OVDepositValLbl.setVisible(false);
}//GEN-LAST:event_OVClearFieldButtonActionPerformed
private void OVSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* OrderVerify object to OrderVerify.insertOrUpdateOV() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the OVIDText field
* to populate the screen with the information that is searched for and
* verified by the popOV() method. If popOV() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean nameCheck = false, accountCheck = false, mediaCheck = false,
contentCheck = false,paymentCheck = false, depositCheck = false;
String nameComment = "", accountComment = "", mediaComment = "",
contentComment = "", paymentComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if OV check fails
if(OVCorrectNamePassRb.isSelected()){
nameCheck = Boolean.TRUE;
}
else if(OVCorrectNameFailRb.isSelected()){
nameCheck = Boolean.FALSE;
nameComment = OVNameFailText.getText();
}
if(OVAcctNumPassRb.isSelected()){
accountCheck = Boolean.TRUE;
}
else if(OVAcctNumFailRb.isSelected()){
accountCheck = Boolean.FALSE;
accountComment = OVAcctNumFailText.getText();
}
if(OVMediaNumPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(OVMediaNumFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = OVMediaFailText.getText();
}
if(OVContentPassRb.isSelected()){
contentCheck = (Boolean.TRUE);
}
else if(OVContentFailRb.isSelected()){
contentCheck = (Boolean.FALSE);
contentComment = (OVContentFailText.getText());
}
if(OVPayTypePassRb.isSelected()){
paymentCheck = (Boolean.TRUE);
}
else if(OVPayTypeFailRb.isSelected()){
paymentCheck = (Boolean.FALSE);
paymentComment = (OVPayTypeFailText.getText());
}
if (OVDepositPassRb.isSelected()){
depositCheck = (Boolean.TRUE);
}
else if(OVDepositFailRb.isSelected()){
depositCheck = (Boolean.FALSE);
depositComment = (OVDepositFailText.getText());
}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected()){
correctiveActionComment = (OVCommentsText.getText());
}
//Create new OV object with screen data to be passed to insertOrUpdateOV()
OrderVerify newOV = new OrderVerify((Integer.parseInt(OVerIDText.getText())),Login.emp,
Order.getOrder(Integer.parseInt(OVOrderIDText.getText())),
nameCheck, accountCheck, mediaCheck, contentCheck, paymentCheck,
depositCheck, nameComment, accountComment, mediaComment, contentComment,
paymentComment, depositComment,correctiveActionComment);
//Object that is returned verifies that the object was created
newOV = OrderVerify.insertOrUpdateOV(newOV);
//prepare screen for popOV()
- OVerIDText.setText(String.valueOf(newOV.getVerId()));
+ OVerIDText.setText(String.valueOf(newOV.getVerID()));
OVOrderIDText.setText("");
//Record is searched for and verified a second time through popOV()
if(popOV()){
OVButtonLbl.setText("Create/Update Successful");}
}//GEN-LAST:event_OVSubmitButtonActionPerformed
//</editor-fold>
private void OrderStatusCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderStatusCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_OrderStatusCBActionPerformed
private void emOrdersLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_emOrdersLstValueChanged
// TODO add your handling code here:
}//GEN-LAST:event_emOrdersLstValueChanged
private void custOrdLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_custOrdLstValueChanged
//Add code for customer orders
}//GEN-LAST:event_custOrdLstValueChanged
private void EmpTypeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpTypeCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_EmpTypeCBActionPerformed
private void OrderNumberCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderNumberCBActionPerformed
if (this.OrderNumberCB.getSelectedIndex() != -1)
this.selectOrderByIndex(this.OrderNumberCB.getSelectedIndex());
}//GEN-LAST:event_OrderNumberCBActionPerformed
private void OrderUpdateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void OVContentValLblMouseClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OVContentValLblMouseClick
//Brad: popup content in JOption pane for easy access when verifying order
JOptionPane.showMessageDialog(null, workingOV.getOrder().getContent());
}//GEN-LAST:event_OVContentValLblMouseClick
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: InventoryItem Search,Submit,Clear Buttons">
private void InvClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvClearButtonActionPerformed
// Clear Inventory data
InvItemIdText.setText("");
InvManufacturerIdText.setText("");
InvItemNameText.setText("");
InvOnHandText.setText("");
InvOnOrderText.setText("");
InvDeliveryDateText.setText("");
}//GEN-LAST:event_InvClearButtonActionPerformed
private void InvOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvOrderButtonActionPerformed
}//GEN-LAST:event_InvOrderButtonActionPerformed
private void InvSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvSearchButtonActionPerformed
if(popII()){
InvButtonLbl.setText("Item(s) found");
}
}//GEN-LAST:event_InvSearchButtonActionPerformed
private Boolean popII(){ /*
* Brad Clawson: Populates Inventory Item tab by searching either ItemID Number,
* Manufacturer, or name but not by more than one field.
*/
//search by ITEMID if ManID and ItemName are null or empty
if ((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("ITEMID", InvItemIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by MANID if ITEMID and ItemName are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("MANID", InvManufacturerIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by ItemName if ManID and ITEMID are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("Name", InvItemNameText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//if search criteria are all null or empty, return false with notification
else if((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Please enter a search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
InvItemNameText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
|| (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//populate Inventory Item Tab fields
InvItemIdText.setText(String.valueOf(workingII.getItemNumber()));
InvManufacturerIdText.setText(String.valueOf(workingII.getManufacturerID()));
InvItemNameText.setText(workingII.getName());
InvOnHandText.setText(String.valueOf(workingII.getQtyOnHand()));
InvOnOrderText.setText(String.valueOf(workingII.getQtyOnOrder()));
InvDeliveryDateText.setText(workingII.getDeliveryDate());
return true;
}
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="GUI Variable Declarations">
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField CUSTIDCB;
private javax.swing.JLabel CUSTIDLbl;
private javax.swing.JLabel CustActiveOrderLbl;
private javax.swing.JLabel CustCityLbl;
private javax.swing.JTextField CustCityText;
private javax.swing.JButton CustClearButton;
private javax.swing.JButton CustCreateButton;
private javax.swing.JLabel CustEmailLbl;
private javax.swing.JTextField CustEmailText;
private javax.swing.JLabel CustFNameLbl;
private javax.swing.JTextField CustFNameText;
private javax.swing.JButton CustFindButton;
private javax.swing.JLabel CustLNameLbl;
private javax.swing.JTextField CustLNameText;
private javax.swing.JScrollPane CustOrderListBox;
private javax.swing.JLabel CustOrderListBoxLbl;
private javax.swing.JLabel CustOrgLbl;
private javax.swing.JTextField CustOrgText;
private javax.swing.JLabel CustPhoneLbl;
private javax.swing.JTextField CustPhoneText;
private javax.swing.JComboBox CustStateCB;
private javax.swing.JLabel CustStateLbl;
private javax.swing.JLabel CustStreet1Lbl;
private javax.swing.JTextField CustStreet1Text;
private javax.swing.JLabel CustStreet2Lbl;
private javax.swing.JTextField CustStreet2Text;
private javax.swing.JLabel CustZipLbl;
private javax.swing.JTextField CustZipText;
private javax.swing.JPanel CustomerInfoPanel;
private javax.swing.JTextField EMPIDCB;
private javax.swing.JLabel EMPIDLbl;
private javax.swing.JLabel EmpActiveOrderLbl1;
private javax.swing.JButton EmpClearButton;
private javax.swing.JTextField EmpEmail;
private javax.swing.JLabel EmpFNameLbl;
private javax.swing.JTextField EmpFNameText;
private javax.swing.JLabel EmpLNameLbl;
private javax.swing.JTextField EmpLNameText;
private javax.swing.JScrollPane EmpOrderLB;
private javax.swing.JLabel EmpOrderLbl;
private javax.swing.JPasswordField EmpPass;
private javax.swing.JPasswordField EmpPassConfirm;
private javax.swing.JButton EmpSearchButton;
private javax.swing.JLabel EmpSearchLbl;
private javax.swing.JButton EmpSubmitButton;
private javax.swing.JComboBox EmpTypeCB;
private javax.swing.JLabel EmpTypeLbl;
private javax.swing.JPanel EmployeeInfoPanel;
private javax.swing.JLabel InvButtonLbl;
private javax.swing.JButton InvClearButton;
private javax.swing.JLabel InvDeliveryDateLbl;
private javax.swing.JTextField InvDeliveryDateText;
private javax.swing.JLabel InvItemIDLbl;
private javax.swing.JTextField InvItemIdText;
private javax.swing.JLabel InvItemNameLbl;
private javax.swing.JTextField InvItemNameText;
private javax.swing.JLabel InvManufacturerIdLbl;
private javax.swing.JTextField InvManufacturerIdText;
private javax.swing.JLabel InvManufacturerItemLbl;
private javax.swing.JList InvManufacturerItemList;
private javax.swing.JScrollPane InvManufacturerItemScrollPane;
private javax.swing.JTextField InvOnHandText;
private javax.swing.JTextField InvOnOrderText;
private javax.swing.JButton InvOrderButton;
private javax.swing.JLabel InvOrderIdLbl;
private javax.swing.JTextField InvOrderIdText;
private javax.swing.JLabel InvQtyOnHandLbl;
private javax.swing.JLabel InvQtyOnOrderLbl;
private javax.swing.JButton InvSearchButton;
private javax.swing.JLabel InvSearchLbl5;
private javax.swing.JPanel InventoryPanel;
private javax.swing.JButton LoginButton;
private javax.swing.JLabel LoginEMPIDLbl;
private javax.swing.JTextField LoginEMPIDTxt;
private javax.swing.JPanel LoginPanel;
private javax.swing.JLabel LoginPassLbl;
private javax.swing.JPasswordField LoginPassText;
private javax.swing.JButton LogoutButton;
private javax.swing.ButtonGroup OVAccountBG;
private javax.swing.JRadioButton OVAcctNumFailRb;
private javax.swing.JTextField OVAcctNumFailText;
private javax.swing.JLabel OVAcctNumLbl;
private javax.swing.JRadioButton OVAcctNumPassRb;
private javax.swing.JComboBox OVAssignEmpCB;
private javax.swing.JLabel OVAssignEmpLbl;
private javax.swing.JLabel OVAssignedToLbl;
private javax.swing.JLabel OVButtonLbl;
private javax.swing.JButton OVClearFieldButton;
private javax.swing.JLabel OVCommentsLbl;
private javax.swing.JScrollPane OVCommentsTB;
private javax.swing.JTextArea OVCommentsText;
private javax.swing.ButtonGroup OVContentBG;
private javax.swing.JRadioButton OVContentFailRb;
private javax.swing.JTextField OVContentFailText;
private javax.swing.JLabel OVContentLbl;
private javax.swing.JRadioButton OVContentPassRb;
private javax.swing.JLabel OVContentValLbl;
private javax.swing.JRadioButton OVCorrectNameFailRb;
private javax.swing.JLabel OVCorrectNameLbl;
private javax.swing.JRadioButton OVCorrectNamePassRb;
private javax.swing.JLabel OVCreateByLbl;
private javax.swing.JLabel OVCustIDValLbl;
private javax.swing.JLabel OVCustNameValLbl;
private javax.swing.ButtonGroup OVDepositBG;
private javax.swing.JRadioButton OVDepositFailRb;
private javax.swing.JTextField OVDepositFailText;
private javax.swing.JLabel OVDepositLbl;
private javax.swing.JRadioButton OVDepositPassRb;
private javax.swing.JLabel OVDepositValLbl;
private javax.swing.JLabel OVFailLbl;
private javax.swing.ButtonGroup OVMediaBG;
private javax.swing.JLabel OVMediaCatValLbl;
private javax.swing.JTextField OVMediaFailText;
private javax.swing.JRadioButton OVMediaNumFailRb;
private javax.swing.JLabel OVMediaNumLbl;
private javax.swing.JRadioButton OVMediaNumPassRb;
private javax.swing.ButtonGroup OVNameBG;
private javax.swing.JTextField OVNameFailText;
private javax.swing.JLabel OVNumberLbl;
private javax.swing.JTextField OVOrderIDText;
private javax.swing.JLabel OVOrderNumLbl;
private javax.swing.JLabel OVPassLbl;
private javax.swing.JRadioButton OVPayTypeFailRb;
private javax.swing.JTextField OVPayTypeFailText;
private javax.swing.JLabel OVPayTypePassLbl;
private javax.swing.JRadioButton OVPayTypePassRb;
private javax.swing.JLabel OVPayTypeValLbl;
private javax.swing.ButtonGroup OVPaymentBG;
private javax.swing.JLabel OVReasonLbl;
private javax.swing.JButton OVSearchButton;
private javax.swing.JButton OVSubmitButton;
private javax.swing.JLabel OVVerifyByLbl;
private javax.swing.JTextField OVerIDText;
private javax.swing.JRadioButton OrderAccountPayRB;
private javax.swing.JLabel OrderAssignedToLbl;
private javax.swing.JTextField OrderCUSTIDText;
private javax.swing.JButton OrderClearFieldsButton;
private javax.swing.JLabel OrderContentLbl;
private javax.swing.JTextField OrderContentText;
private javax.swing.JButton OrderCreateBtn;
private javax.swing.JLabel OrderCreatedByLbl;
private javax.swing.JLabel OrderCustNumberLbl;
private javax.swing.JRadioButton OrderDeliverPayRB;
private javax.swing.JLabel OrderDepositLbl;
private javax.swing.JTextField OrderDepositText;
private javax.swing.ButtonGroup OrderEngMediaBG;
private javax.swing.JPanel OrderInfoPanel;
private javax.swing.JLabel OrderMediaCatNumLbl;
private javax.swing.JTextField OrderMediaCatNumText;
private javax.swing.JComboBox OrderMediaStatusCB;
private javax.swing.JLabel OrderMediaStatusLbl;
private javax.swing.JLabel OrderMediaTypeLbl;
private javax.swing.JComboBox OrderNumberCB;
private javax.swing.JLabel OrderNumberLbl;
private javax.swing.ButtonGroup OrderPayTypeBG;
private javax.swing.JLabel OrderPaymentTypeLbl;
private javax.swing.JButton OrderSearchButton;
private javax.swing.JLabel OrderSearchLbl;
private javax.swing.JComboBox OrderStatusCB;
private javax.swing.JLabel OrderStatusLbl;
private javax.swing.JTabbedPane OrderTabbedPane;
private javax.swing.JLabel OrderTotalLbl;
private javax.swing.JTextField OrderTotalText;
private javax.swing.ButtonGroup OrderTypeBG;
private javax.swing.JRadioButton OrderTypePlaqueRB;
private javax.swing.JRadioButton OrderTypeShirtRB;
private javax.swing.JRadioButton OrderTypeTrophyRB;
private javax.swing.JButton OrderUpdateBtn;
private javax.swing.JLabel OrderVerifyByLbl;
private javax.swing.JPanel OrderVerifyPanel;
private javax.swing.JLabel QAAssignedToLbl;
private javax.swing.JLabel QAButtonLbl;
private javax.swing.JButton QAClearButton;
private javax.swing.JLabel QACommentLbl;
private javax.swing.ButtonGroup QAContentBG;
private javax.swing.JRadioButton QAContentCheckFailRb;
private javax.swing.JRadioButton QAContentCheckPassRb;
private javax.swing.JTextField QAContentFailText;
private javax.swing.JLabel QAContentLbl;
private javax.swing.JScrollPane QACorrectiveActionTB;
private javax.swing.JTextArea QACorrectiveActionText;
private javax.swing.JLabel QACreatedByLbl;
private javax.swing.JLabel QAFailCommentLbl;
private javax.swing.JLabel QAFailLbl;
private javax.swing.JLabel QAIDLbl;
private javax.swing.JTextField QAIDText;
private javax.swing.ButtonGroup QAMediaBG;
private javax.swing.JRadioButton QAMediaCheckFailRb;
private javax.swing.JRadioButton QAMediaCheckPassRb;
private javax.swing.JTextField QAMediaFailText;
private javax.swing.ButtonGroup QAMediaFinishBG;
private javax.swing.JRadioButton QAMediaFinishCheckFailRb;
private javax.swing.JRadioButton QAMediaFinishCheckPassRb;
private javax.swing.JTextField QAMediaFinishFailText;
private javax.swing.JLabel QAMediaFinishLbl;
private javax.swing.JLabel QAMediaLbl;
private javax.swing.JLabel QAOrderIDLbl;
private javax.swing.JTextField QAOrderIDText;
private javax.swing.JPanel QAPanel;
private javax.swing.JLabel QAPassLbl;
private javax.swing.JButton QASearchButton;
private javax.swing.JButton QASubmitButton;
private javax.swing.JLabel QAVerifiedByLbl;
private javax.swing.ButtonGroup QAWorkmanshipBG;
private javax.swing.JRadioButton QAWorkmanshipCheckFailRb;
private javax.swing.JRadioButton QAWorkmanshipCheckPassRb;
private javax.swing.JTextField QAWorkmanshipFailText;
private javax.swing.JLabel QAWorkmanshipLbl;
private javax.swing.JTabbedPane WSCInterface;
private javax.swing.JList custOrdLst;
private javax.swing.JList emOrdersLst;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
protected javax.swing.JLabel lblLoginStatus;
// End of variables declaration//GEN-END:variables
//</editor-fold>
}
| false | true | public WilliamsSpecialtyGUI() {
initComponents();
HideEmpPassword();
/* //Brad: make all tabs except login invisible Login action will set user access
* CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/ }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
OrderPayTypeBG = new javax.swing.ButtonGroup();
OrderTypeBG = new javax.swing.ButtonGroup();
OrderEngMediaBG = new javax.swing.ButtonGroup();
OVAccountBG = new javax.swing.ButtonGroup();
OVNameBG = new javax.swing.ButtonGroup();
QAContentBG = new javax.swing.ButtonGroup();
QAMediaBG = new javax.swing.ButtonGroup();
QAMediaFinishBG = new javax.swing.ButtonGroup();
QAWorkmanshipBG = new javax.swing.ButtonGroup();
OVMediaBG = new javax.swing.ButtonGroup();
OVContentBG = new javax.swing.ButtonGroup();
OVPaymentBG = new javax.swing.ButtonGroup();
OVDepositBG = new javax.swing.ButtonGroup();
WSCInterface = new javax.swing.JTabbedPane();
LoginPanel = new javax.swing.JPanel();
LoginButton = new javax.swing.JButton();
LoginEMPIDTxt = new javax.swing.JTextField();
LoginEMPIDLbl = new javax.swing.JLabel();
LoginPassLbl = new javax.swing.JLabel();
LoginPassText = new javax.swing.JPasswordField();
LogoutButton = new javax.swing.JButton();
lblLoginStatus = new javax.swing.JLabel();
CustomerInfoPanel = new javax.swing.JPanel();
CustFNameText = new javax.swing.JTextField();
CustLNameText = new javax.swing.JTextField();
CustOrgText = new javax.swing.JTextField();
CustStreet1Text = new javax.swing.JTextField();
CustStreet2Text = new javax.swing.JTextField();
CustFNameLbl = new javax.swing.JLabel();
CustLNameLbl = new javax.swing.JLabel();
CustOrgLbl = new javax.swing.JLabel();
CustStreet1Lbl = new javax.swing.JLabel();
CustStreet2Lbl = new javax.swing.JLabel();
CustCityText = new javax.swing.JTextField();
CustZipText = new javax.swing.JTextField();
CustCityLbl = new javax.swing.JLabel();
CustZipLbl = new javax.swing.JLabel();
CustFindButton = new javax.swing.JButton();
CustCreateButton = new javax.swing.JButton();
CustOrderListBox = new javax.swing.JScrollPane();
custOrdLst = new javax.swing.JList();
CustOrderListBoxLbl = new javax.swing.JLabel();
CustClearButton = new javax.swing.JButton();
CustActiveOrderLbl = new javax.swing.JLabel();
CUSTIDLbl = new javax.swing.JLabel();
CustStateCB = new javax.swing.JComboBox();
CustStateLbl = new javax.swing.JLabel();
InvSearchLbl5 = new javax.swing.JLabel();
CustPhoneLbl = new javax.swing.JLabel();
CustPhoneText = new javax.swing.JTextField();
CustEmailLbl = new javax.swing.JLabel();
CustEmailText = new javax.swing.JTextField();
CUSTIDCB = new javax.swing.JTextField();
OrderTabbedPane = new javax.swing.JTabbedPane();
OrderInfoPanel = new javax.swing.JPanel();
OrderNumberLbl = new javax.swing.JLabel();
OrderDeliverPayRB = new javax.swing.JRadioButton();
OrderAccountPayRB = new javax.swing.JRadioButton();
OrderDepositLbl = new javax.swing.JLabel();
OrderDepositText = new javax.swing.JTextField();
OrderTypeShirtRB = new javax.swing.JRadioButton();
OrderTypeTrophyRB = new javax.swing.JRadioButton();
OrderTypePlaqueRB = new javax.swing.JRadioButton();
OrderContentLbl = new javax.swing.JLabel();
OrderContentText = new javax.swing.JTextField();
OrderMediaCatNumLbl = new javax.swing.JLabel();
OrderMediaCatNumText = new javax.swing.JTextField();
OrderMediaTypeLbl = new javax.swing.JLabel();
OrderCustNumberLbl = new javax.swing.JLabel();
OrderCUSTIDText = new javax.swing.JTextField();
OrderPaymentTypeLbl = new javax.swing.JLabel();
OrderClearFieldsButton = new javax.swing.JButton();
OrderCreateBtn = new javax.swing.JButton();
OrderSearchButton = new javax.swing.JButton();
OrderMediaStatusCB = new javax.swing.JComboBox();
OrderStatusLbl = new javax.swing.JLabel();
OrderStatusCB = new javax.swing.JComboBox();
OrderMediaStatusLbl = new javax.swing.JLabel();
OrderTotalLbl = new javax.swing.JLabel();
OrderTotalText = new javax.swing.JTextField();
OrderVerifyByLbl = new javax.swing.JLabel();
OrderAssignedToLbl = new javax.swing.JLabel();
OrderCreatedByLbl = new javax.swing.JLabel();
OrderNumberCB = new javax.swing.JComboBox();
OrderSearchLbl = new javax.swing.JLabel();
OrderUpdateBtn = new javax.swing.JButton();
OrderVerifyPanel = new javax.swing.JPanel();
OVSubmitButton = new javax.swing.JButton();
OVClearFieldButton = new javax.swing.JButton();
OVSearchButton = new javax.swing.JButton();
OVCorrectNameLbl = new javax.swing.JLabel();
OVAcctNumLbl = new javax.swing.JLabel();
OVMediaNumLbl = new javax.swing.JLabel();
OVContentLbl = new javax.swing.JLabel();
OVCorrectNamePassRb = new javax.swing.JRadioButton();
OVAcctNumPassRb = new javax.swing.JRadioButton();
OVMediaNumPassRb = new javax.swing.JRadioButton();
OVContentPassRb = new javax.swing.JRadioButton();
OVCorrectNameFailRb = new javax.swing.JRadioButton();
OVAcctNumFailRb = new javax.swing.JRadioButton();
OVMediaNumFailRb = new javax.swing.JRadioButton();
OVContentFailRb = new javax.swing.JRadioButton();
OVCommentsTB = new javax.swing.JScrollPane();
OVCommentsText = new javax.swing.JTextArea();
OVCommentsLbl = new javax.swing.JLabel();
OVNameFailText = new javax.swing.JTextField();
OVAcctNumFailText = new javax.swing.JTextField();
OVMediaFailText = new javax.swing.JTextField();
OVContentFailText = new javax.swing.JTextField();
OVPassLbl = new javax.swing.JLabel();
OVFailLbl = new javax.swing.JLabel();
OVReasonLbl = new javax.swing.JLabel();
OVDepositPassRb = new javax.swing.JRadioButton();
OVDepositLbl = new javax.swing.JLabel();
OVDepositFailRb = new javax.swing.JRadioButton();
OVPayTypeFailRb = new javax.swing.JRadioButton();
OVPayTypePassLbl = new javax.swing.JLabel();
OVDepositFailText = new javax.swing.JTextField();
OVPayTypeFailText = new javax.swing.JTextField();
OVPayTypePassRb = new javax.swing.JRadioButton();
OVNumberLbl = new javax.swing.JLabel();
OVerIDText = new javax.swing.JTextField();
OVCustNameValLbl = new javax.swing.JLabel();
OVCustIDValLbl = new javax.swing.JLabel();
OVMediaCatValLbl = new javax.swing.JLabel();
OVContentValLbl = new javax.swing.JLabel();
OVPayTypeValLbl = new javax.swing.JLabel();
OVDepositValLbl = new javax.swing.JLabel();
OVAssignEmpCB = new javax.swing.JComboBox();
OVAssignEmpLbl = new javax.swing.JLabel();
OVOrderNumLbl = new javax.swing.JLabel();
OVOrderIDText = new javax.swing.JTextField();
OVVerifyByLbl = new javax.swing.JLabel();
OVCreateByLbl = new javax.swing.JLabel();
OVAssignedToLbl = new javax.swing.JLabel();
OVButtonLbl = new javax.swing.JLabel();
QAPanel = new javax.swing.JPanel();
QASubmitButton = new javax.swing.JButton();
QAClearButton = new javax.swing.JButton();
QASearchButton = new javax.swing.JButton();
QAContentLbl = new javax.swing.JLabel();
QAMediaLbl = new javax.swing.JLabel();
QAMediaFinishLbl = new javax.swing.JLabel();
QAWorkmanshipLbl = new javax.swing.JLabel();
QAContentCheckPassRb = new javax.swing.JRadioButton();
QAMediaCheckPassRb = new javax.swing.JRadioButton();
QAMediaFinishCheckPassRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckPassRb = new javax.swing.JRadioButton();
QAContentCheckFailRb = new javax.swing.JRadioButton();
QAMediaCheckFailRb = new javax.swing.JRadioButton();
QAMediaFinishCheckFailRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckFailRb = new javax.swing.JRadioButton();
QACorrectiveActionTB = new javax.swing.JScrollPane();
QACorrectiveActionText = new javax.swing.JTextArea();
QACommentLbl = new javax.swing.JLabel();
QAContentFailText = new javax.swing.JTextField();
QAMediaFailText = new javax.swing.JTextField();
QAMediaFinishFailText = new javax.swing.JTextField();
QAWorkmanshipFailText = new javax.swing.JTextField();
QAPassLbl = new javax.swing.JLabel();
QAFailLbl = new javax.swing.JLabel();
QAFailCommentLbl = new javax.swing.JLabel();
QAVerifiedByLbl = new javax.swing.JLabel();
QACreatedByLbl = new javax.swing.JLabel();
QAAssignedToLbl = new javax.swing.JLabel();
QAOrderIDLbl = new javax.swing.JLabel();
QAIDLbl = new javax.swing.JLabel();
QAButtonLbl = new javax.swing.JLabel();
QAOrderIDText = new javax.swing.JTextField();
QAIDText = new javax.swing.JTextField();
InventoryPanel = new javax.swing.JPanel();
InvItemIDLbl = new javax.swing.JLabel();
InvManufacturerIdLbl = new javax.swing.JLabel();
InvQtyOnHandLbl = new javax.swing.JLabel();
InvQtyOnOrderLbl = new javax.swing.JLabel();
InvDeliveryDateLbl = new javax.swing.JLabel();
InvOrderButton = new javax.swing.JButton();
InvClearButton = new javax.swing.JButton();
InvSearchButton = new javax.swing.JButton();
InvItemNameLbl = new javax.swing.JLabel();
InvItemNameText = new javax.swing.JTextField();
InvButtonLbl = new javax.swing.JLabel();
InvOnHandText = new javax.swing.JTextField();
InvOnOrderText = new javax.swing.JTextField();
InvDeliveryDateText = new javax.swing.JTextField();
InvItemIdText = new javax.swing.JTextField();
InvManufacturerIdText = new javax.swing.JTextField();
InvOrderIdLbl = new javax.swing.JLabel();
InvOrderIdText = new javax.swing.JTextField();
InvManufacturerItemScrollPane = new javax.swing.JScrollPane();
InvManufacturerItemList = new javax.swing.JList();
InvManufacturerItemLbl = new javax.swing.JLabel();
EmployeeInfoPanel = new javax.swing.JPanel();
EmpFNameText = new javax.swing.JTextField();
EmpLNameText = new javax.swing.JTextField();
EmpFNameLbl = new javax.swing.JLabel();
EmpLNameLbl = new javax.swing.JLabel();
EmpSearchButton = new javax.swing.JButton();
EmpSubmitButton = new javax.swing.JButton();
EmpOrderLB = new javax.swing.JScrollPane();
emOrdersLst = new javax.swing.JList();
EmpOrderLbl = new javax.swing.JLabel();
EmpClearButton = new javax.swing.JButton();
EmpActiveOrderLbl1 = new javax.swing.JLabel();
EMPIDLbl = new javax.swing.JLabel();
EmpTypeCB = new javax.swing.JComboBox();
EmpTypeLbl = new javax.swing.JLabel();
EmpSearchLbl = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
EmpEmail = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
EmpPass = new javax.swing.JPasswordField();
jLabel4 = new javax.swing.JLabel();
EmpPassConfirm = new javax.swing.JPasswordField();
EMPIDCB = new javax.swing.JTextField();
setPreferredSize(new java.awt.Dimension(600, 549));
WSCInterface.setPreferredSize(new java.awt.Dimension(600, 549));
LoginPanel.setDoubleBuffered(false);
LoginButton.setText("Login");
LoginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginButtonActionPerformed(evt);
}
});
LoginEMPIDTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginEMPIDTxtActionPerformed(evt);
}
});
LoginEMPIDLbl.setText("Employee ID");
LoginPassLbl.setText("Password");
LoginPassText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginPassTextActionPerformed(evt);
}
});
LogoutButton.setText("Logout");
LogoutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogoutButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout LoginPanelLayout = new javax.swing.GroupLayout(LoginPanel);
LoginPanel.setLayout(LoginPanelLayout);
LoginPanelLayout.setHorizontalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(260, 260, 260)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, LoginPanelLayout.createSequentialGroup()
.addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(LogoutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginPassLbl))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LoginEMPIDTxt)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblLoginStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(199, Short.MAX_VALUE))
);
LoginPanelLayout.setVerticalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(157, 157, 157)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginEMPIDTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginPassLbl)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblLoginStatus))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LogoutButton)
.addComponent(LoginButton))
.addContainerGap(388, Short.MAX_VALUE))
);
WSCInterface.addTab("Login", LoginPanel);
CustFNameLbl.setText("First Name");
CustLNameLbl.setText("Last Name");
CustOrgLbl.setText("Organization");
CustStreet1Lbl.setText("Street Address Line 1");
CustStreet2Lbl.setText("Street Address Line 2");
CustCityLbl.setText("City");
CustZipLbl.setText("Zip");
CustFindButton.setText("Search");
CustFindButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustFindButtonActionPerformed(evt);
}
});
CustCreateButton.setText("Create/Update");
CustCreateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustCreateButtonActionPerformed(evt);
}
});
custOrdLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
custOrdLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
custOrdLstValueChanged(evt);
}
});
CustOrderListBox.setViewportView(custOrdLst);
CustOrderListBoxLbl.setText("Order(s):");
CustClearButton.setText("Clear Fields");
CustClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustClearButtonActionPerformed(evt);
}
});
CustActiveOrderLbl.setForeground(new java.awt.Color(255, 0, 0));
CustActiveOrderLbl.setText("*Active orders in red");
CUSTIDLbl.setText("Customer Number");
CustStateCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"", "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA",
"ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" }));
CustStateCB.setPreferredSize(new java.awt.Dimension(35, 20));
CustStateCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustStateCBActionPerformed(evt);
}
});
CustStateLbl.setText("State");
InvSearchLbl5.setForeground(new java.awt.Color(255, 51, 51));
InvSearchLbl5.setText("* Use only one field for searches");
CustPhoneLbl.setText("Phone Number");
CustEmailLbl.setText("Email");
javax.swing.GroupLayout CustomerInfoPanelLayout = new javax.swing.GroupLayout(CustomerInfoPanel);
CustomerInfoPanel.setLayout(CustomerInfoPanelLayout);
CustomerInfoPanelLayout.setHorizontalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustEmailLbl)
.addComponent(InvSearchLbl5)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustPhoneLbl)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustStateLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(CustCityLbl)
.addComponent(CustStreet2Lbl)
.addComponent(CustStreet1Lbl)
.addComponent(CustOrgLbl)
.addComponent(CustFNameLbl)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustZipLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CUSTIDLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustActiveOrderLbl)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrderListBoxLbl)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustFindButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustCreateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustClearButton)))
.addContainerGap(286, Short.MAX_VALUE))
);
CustomerInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CustCityText, CustEmailText, CustFNameText, CustLNameText, CustOrgText, CustPhoneText, CustStreet1Text, CustStreet2Text, CustZipText});
CustomerInfoPanelLayout.setVerticalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustOrderListBoxLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustActiveOrderLbl))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CUSTIDLbl)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipLbl)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStateLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustPhoneLbl)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustEmailLbl)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFindButton)
.addComponent(CustCreateButton)
.addComponent(CustClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvSearchLbl5)
.addContainerGap(208, Short.MAX_VALUE))
);
WSCInterface.addTab("Customer Info", CustomerInfoPanel);
OrderNumberLbl.setText("Order Number");
OrderPayTypeBG.add(OrderDeliverPayRB);
OrderDeliverPayRB.setText("Payment on Delivery");
OrderPayTypeBG.add(OrderAccountPayRB);
OrderAccountPayRB.setText("Payment on Account");
OrderDepositLbl.setText("Deposit Amount");
OrderTypeBG.add(OrderTypeShirtRB);
OrderTypeShirtRB.setText("Shirt");
OrderTypeBG.add(OrderTypeTrophyRB);
OrderTypeTrophyRB.setText("Trophy");
OrderTypeBG.add(OrderTypePlaqueRB);
OrderTypePlaqueRB.setText("Plaque");
OrderContentLbl.setText("Printing/Engraving Content:");
OrderMediaCatNumLbl.setText("Media Catalog Number");
OrderMediaTypeLbl.setText("Media Type");
OrderCustNumberLbl.setText("Customer Number");
OrderPaymentTypeLbl.setText("Payment Type");
OrderClearFieldsButton.setText("Clear Fields");
OrderClearFieldsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderClearFieldsButtonActionPerformed(evt);
}
});
OrderCreateBtn.setText("Create");
OrderCreateBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderCreateBtnActionPerformed(evt);
}
});
OrderSearchButton.setText("Search");
OrderSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderSearchButtonActionPerformed(evt);
}
});
OrderMediaStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusLbl.setText("Order Status");
OrderStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderStatusCBActionPerformed(evt);
}
});
OrderMediaStatusLbl.setText("Media Status");
OrderTotalLbl.setText("Estimated Total");
OrderVerifyByLbl.setText("Order Verified by ******");
OrderAssignedToLbl.setText("Work Assigned to ******");
OrderCreatedByLbl.setText("Order Created by ******");
OrderNumberCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderNumberCBActionPerformed(evt);
}
});
OrderSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
OrderSearchLbl.setText("* Use only one field for searches");
OrderUpdateBtn.setText("Update");
javax.swing.GroupLayout OrderInfoPanelLayout = new javax.swing.GroupLayout(OrderInfoPanel);
OrderInfoPanel.setLayout(OrderInfoPanelLayout);
OrderInfoPanelLayout.setHorizontalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderTypeShirtRB)
.addComponent(OrderTypePlaqueRB)
.addComponent(OrderTypeTrophyRB)
.addComponent(OrderStatusLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderAccountPayRB)
.addComponent(OrderDeliverPayRB)
.addComponent(OrderPaymentTypeLbl)
.addComponent(OrderTotalLbl)
.addComponent(OrderMediaTypeLbl)
.addComponent(OrderMediaCatNumLbl)
.addComponent(OrderNumberLbl)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderInfoPanelLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(OrderMediaStatusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderClearFieldsButton)
.addComponent(OrderUpdateBtn)
.addComponent(OrderCreateBtn)
.addComponent(OrderSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(131, Short.MAX_VALUE))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(215, 215, 215)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderVerifyByLbl)
.addComponent(OrderCreatedByLbl))
.addGap(48, 48, 48)
.addComponent(OrderAssignedToLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(OrderDepositLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(371, 371, 371)
.addComponent(OrderSearchLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(331, 331, 331)
.addComponent(OrderContentLbl)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderNumberCB, OrderStatusCB, OrderTotalText});
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderClearFieldsButton, OrderCreateBtn, OrderSearchButton, OrderUpdateBtn});
OrderInfoPanelLayout.setVerticalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumLbl))
.addGap(8, 8, 8)
.addComponent(OrderMediaTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeShirtRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeTrophyRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypePlaqueRB)
.addGap(40, 40, 40)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OrderPaymentTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderAccountPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderDeliverPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositLbl)))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(OrderContentLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(OrderSearchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderCreateBtn)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderUpdateBtn)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusLbl)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderClearFieldsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
.addComponent(OrderSearchLbl)
.addGap(18, 18, 18)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderCreatedByLbl)
.addComponent(OrderAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderVerifyByLbl)
.addGap(51, 51, 51))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderStatusCB, OrderTotalText});
OrderTabbedPane.addTab("Order Info", OrderInfoPanel);
OVSubmitButton.setText("Submit/Assign");
OVSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSubmitButtonActionPerformed(evt);
}
});
OVClearFieldButton.setText("Clear Fields");
OVClearFieldButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVClearFieldButtonActionPerformed(evt);
}
});
OVSearchButton.setText("Search");
OVSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSearchButtonActionPerformed(evt);
}
});
OVCorrectNameLbl.setText("Correct Name");
OVAcctNumLbl.setText("Correct Account Number");
OVMediaNumLbl.setText("Valid Media Cat. #");
OVContentLbl.setText("Valid Content");
OVNameBG.add(OVCorrectNamePassRb);
OVCorrectNamePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNamePassRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumPassRb);
OVAcctNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumPassRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumPassRb);
OVMediaNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumPassRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentPassRb);
OVContentPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentPassRbActionPerformed(evt);
}
});
OVNameBG.add(OVCorrectNameFailRb);
OVCorrectNameFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNameFailRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumFailRb);
OVAcctNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumFailRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumFailRb);
OVMediaNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumFailRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentFailRb);
OVContentFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentFailRbActionPerformed(evt);
}
});
OVCommentsText.setColumns(20);
OVCommentsText.setRows(5);
OVCommentsTB.setViewportView(OVCommentsText);
OVCommentsLbl.setText("Additional Comments");
OVNameFailText.setEditable(false);
OVAcctNumFailText.setEditable(false);
OVMediaFailText.setEditable(false);
OVContentFailText.setEditable(false);
OVPassLbl.setText("Pass");
OVFailLbl.setText("Fail");
OVReasonLbl.setText("Reason for Failure");
OVDepositBG.add(OVDepositPassRb);
OVDepositPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositPassRbActionPerformed(evt);
}
});
OVDepositLbl.setText("Sufficient Deposit");
OVDepositBG.add(OVDepositFailRb);
OVDepositFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositFailRbActionPerformed(evt);
}
});
OVPaymentBG.add(OVPayTypeFailRb);
OVPayTypeFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypeFailRbActionPerformed(evt);
}
});
OVPayTypePassLbl.setText("Payment Type");
OVDepositFailText.setEditable(false);
OVPayTypeFailText.setEditable(false);
OVPaymentBG.add(OVPayTypePassRb);
OVPayTypePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypePassRbActionPerformed(evt);
}
});
OVNumberLbl.setText("Verification Number");
OVContentValLbl.setToolTipText("");
OVContentValLbl.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
OVContentValLblMouseClick(evt);
}
});
OVAssignEmpCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OVAssignEmpLbl.setText("Assign Printer/Engraver");
OVOrderNumLbl.setText("Order Number");
OVVerifyByLbl.setText("Order Verified by ******");
OVCreateByLbl.setText("Order Created by ******");
OVAssignedToLbl.setText("Work Assigned to ******");
OVButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
javax.swing.GroupLayout OrderVerifyPanelLayout = new javax.swing.GroupLayout(OrderVerifyPanel);
OrderVerifyPanel.setLayout(OrderVerifyPanelLayout);
OrderVerifyPanelLayout.setHorizontalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVNumberLbl)
.addComponent(OVOrderNumLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVCorrectNameLbl)
.addComponent(OVAcctNumLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVContentLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVDepositLbl))
.addGap(15, 15, 15)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositPassRb)
.addComponent(OVPayTypePassRb)
.addComponent(OVContentPassRb)
.addComponent(OVMediaNumPassRb)
.addComponent(OVAcctNumPassRb)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVPassLbl))
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositFailRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVContentFailRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVFailLbl))
.addComponent(OVMediaNumFailRb, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVNameFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVReasonLbl))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVButtonLbl)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVVerifyByLbl)
.addComponent(OVCreateByLbl))
.addGap(48, 48, 48)
.addComponent(OVAssignedToLbl))
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OVAssignEmpLbl))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVDepositValLbl)
.addComponent(OVPayTypeValLbl)
.addComponent(OVContentValLbl)
.addComponent(OVMediaCatValLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVCustNameValLbl)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVSubmitButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVClearFieldButton)))
.addGap(373, 419, Short.MAX_VALUE))))
);
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVAcctNumFailText, OVContentFailText, OVMediaFailText, OVNameFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVDepositFailText, OVPayTypeFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVOrderIDText, OVerIDText});
OrderVerifyPanelLayout.setVerticalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVOrderNumLbl)
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVNumberLbl)
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVPassLbl)
.addComponent(OVFailLbl)
.addComponent(OVReasonLbl)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVCustNameValLbl)
.addComponent(OVCorrectNameLbl)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVNameFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVAcctNumLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVAcctNumPassRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVMediaCatValLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVMediaNumPassRb)
.addComponent(OVMediaNumFailRb)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVContentValLbl)
.addComponent(OVContentLbl)
.addComponent(OVContentPassRb)
.addComponent(OVContentFailRb)
.addComponent(OVContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVPayTypeValLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVPayTypePassRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositValLbl)
.addComponent(OVDepositLbl)
.addComponent(OVDepositPassRb)
.addComponent(OVDepositFailRb)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVAssignEmpLbl)
.addComponent(OVCommentsLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVSearchButton)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVClearFieldButton)
.addComponent(OVSubmitButton))))
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addComponent(OVButtonLbl)
.addGap(1, 1, 1)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVCreateByLbl)
.addComponent(OVAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVVerifyByLbl)
.addContainerGap(176, Short.MAX_VALUE))
);
OrderTabbedPane.addTab("Order Verify", OrderVerifyPanel);
QASubmitButton.setText("Submit");
QASubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASubmitButtonActionPerformed(evt);
}
});
QAClearButton.setText("Clear Fields");
QAClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAClearButtonActionPerformed(evt);
}
});
QASearchButton.setText("Search");
QASearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASearchButtonActionPerformed(evt);
}
});
QAContentLbl.setText("Correct Order Content");
QAMediaLbl.setText("Correct Order Media");
QAMediaFinishLbl.setText("Media Finish");
QAWorkmanshipLbl.setText("Workmanship");
QAContentBG.add(QAContentCheckPassRb);
QAContentCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckPassRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckPassRb);
QAMediaCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckPassRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckPassRb);
QAMediaFinishCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckPassRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckPassRb);
QAWorkmanshipCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckPassRbActionPerformed(evt);
}
});
QAContentBG.add(QAContentCheckFailRb);
QAContentCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckFailRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckFailRb);
QAMediaCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckFailRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckFailRb);
QAMediaFinishCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckFailRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckFailRb);
QAWorkmanshipCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckFailRbActionPerformed(evt);
}
});
QACorrectiveActionText.setColumns(20);
QACorrectiveActionText.setRows(5);
QACorrectiveActionTB.setViewportView(QACorrectiveActionText);
QACommentLbl.setText("Comments");
QAPassLbl.setText("Pass");
QAFailLbl.setText("Fail");
QAFailCommentLbl.setText("Reason for Failure");
QAVerifiedByLbl.setText("Order Verified by ******");
QACreatedByLbl.setText("Order Created by ******");
QAAssignedToLbl.setText("Work Assigned to ******");
QAOrderIDLbl.setText("Order Number");
QAIDLbl.setText("QA Inspection Number");
QAButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
QAButtonLbl.setText("* Use only one field for searches");
javax.swing.GroupLayout QAPanelLayout = new javax.swing.GroupLayout(QAPanel);
QAPanel.setLayout(QAPanelLayout);
QAPanelLayout.setHorizontalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAOrderIDLbl)
.addComponent(QAIDLbl))
.addGap(23, 23, 23)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAVerifiedByLbl)
.addComponent(QACreatedByLbl))
.addGap(48, 48, 48)
.addComponent(QAAssignedToLbl))
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAMediaLbl)
.addComponent(QAMediaFinishLbl)
.addComponent(QAWorkmanshipLbl)
.addComponent(QAContentLbl))
.addGap(17, 17, 17)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAPassLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentCheckFailRb)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAFailLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAFailCommentLbl)))
.addComponent(QACommentLbl)
.addGroup(QAPanelLayout.createSequentialGroup()
.addComponent(QASearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QASubmitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAClearButton))
.addComponent(QAOrderIDText, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
.addComponent(QAIDText)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)))
.addContainerGap(197, Short.MAX_VALUE))
);
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAContentFailText, QAMediaFailText, QAMediaFinishFailText, QAWorkmanshipFailText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAIDText, QAOrderIDText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAClearButton, QASearchButton, QASubmitButton});
QAPanelLayout.setVerticalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAOrderIDLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAIDLbl))
.addGap(24, 24, 24)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QAPassLbl)
.addComponent(QAFailLbl)
.addComponent(QAFailCommentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentCheckFailRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAContentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAMediaLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAMediaFinishLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAWorkmanshipLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addComponent(QACommentLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QASearchButton)
.addComponent(QASubmitButton)
.addComponent(QAClearButton))
.addGap(2, 2, 2)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QACreatedByLbl)
.addComponent(QAAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAVerifiedByLbl)
.addGap(88, 88, 88))
);
OrderTabbedPane.addTab("Quality Assurance", QAPanel);
WSCInterface.addTab("Order", OrderTabbedPane);
InvItemIDLbl.setText("Item Number");
InvManufacturerIdLbl.setText("Manufacturer");
InvQtyOnHandLbl.setText("On Hand");
InvQtyOnOrderLbl.setText("On Order");
InvDeliveryDateLbl.setText("Delivery Date");
InvOrderButton.setText("Order/Mark Sold");
InvOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvOrderButtonActionPerformed(evt);
}
});
InvClearButton.setText("Clear Fields");
InvClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvClearButtonActionPerformed(evt);
}
});
InvSearchButton.setText("Search");
InvSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvSearchButtonActionPerformed(evt);
}
});
InvItemNameLbl.setText("Item Name");
InvButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
InvButtonLbl.setText("* Use only one field for searches");
InvOrderIdLbl.setText("Order");
InvManufacturerItemList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
InvManufacturerItemScrollPane.setViewportView(InvManufacturerItemList);
InvManufacturerItemLbl.setText("Items:");
javax.swing.GroupLayout InventoryPanelLayout = new javax.swing.GroupLayout(InventoryPanel);
InventoryPanel.setLayout(InventoryPanelLayout);
InventoryPanelLayout.setHorizontalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(137, 137, 137)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvDeliveryDateLbl)
.addComponent(InvQtyOnOrderLbl)
.addComponent(InvQtyOnHandLbl)
.addComponent(InvItemNameLbl)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvItemIDLbl)
.addComponent(InvSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvOrderIdLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOrderButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(InvOnOrderText)
.addComponent(InvOnHandText)
.addComponent(InvItemNameText)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvItemIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvClearButton))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvManufacturerItemLbl)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(InvButtonLbl))
.addContainerGap(294, Short.MAX_VALUE))
);
InventoryPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {InvClearButton, InvDeliveryDateText, InvItemIdText, InvItemNameText, InvManufacturerIdText, InvOnHandText, InvOnOrderText, InvOrderButton, InvOrderIdText, InvSearchButton});
InventoryPanelLayout.setVerticalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(93, 93, 93)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvOrderIdLbl)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvItemIDLbl)
.addComponent(InvItemIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvItemNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvItemNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnHandText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnHandLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnOrderText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnOrderLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvDeliveryDateLbl)))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(InvManufacturerItemLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvSearchButton)
.addComponent(InvOrderButton)
.addComponent(InvClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvButtonLbl)
.addContainerGap(307, Short.MAX_VALUE))
);
WSCInterface.addTab("Inventory", InventoryPanel);
EmpFNameLbl.setText("First Name");
EmpLNameLbl.setText("Last Name");
EmpSearchButton.setText("Search");
EmpSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSearchButtonActionPerformed(evt);
}
});
EmpSubmitButton.setText("Create/Update");
EmpSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSubmitButtonActionPerformed(evt);
}
});
emOrdersLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
emOrdersLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
emOrdersLstValueChanged(evt);
}
});
EmpOrderLB.setViewportView(emOrdersLst);
EmpOrderLbl.setText("Order(s):");
EmpClearButton.setText("Clear Fields");
EmpClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpClearButtonActionPerformed(evt);
}
});
EmpActiveOrderLbl1.setForeground(new java.awt.Color(255, 0, 0));
EmpActiveOrderLbl1.setText("*Active orders in red");
EMPIDLbl.setText("Employee id");
EmpTypeCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TS", "Item 1", "Item 2", "Item 3", "Item 4" }));
EmpTypeCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpTypeCBActionPerformed(evt);
}
});
EmpTypeLbl.setText("Employee Type");
EmpSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
EmpSearchLbl.setText("* Use only one field for searches");
jLabel1.setText("Email Address");
jLabel3.setText("Login Password");
jLabel4.setText("Confirm Password");
javax.swing.GroupLayout EmployeeInfoPanelLayout = new javax.swing.GroupLayout(EmployeeInfoPanel);
EmployeeInfoPanel.setLayout(EmployeeInfoPanelLayout);
EmployeeInfoPanelLayout.setHorizontalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(135, 135, 135)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(EmpTypeLbl)
.addComponent(jLabel1)
.addComponent(EmpLNameLbl)
.addComponent(EmpFNameLbl)
.addComponent(EMPIDLbl))
.addGap(27, 27, 27)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(EmpActiveOrderLbl1))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EmpOrderLbl)
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EmpSearchLbl)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addComponent(EmpSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EmpSubmitButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpClearButton)))
.addContainerGap(241, Short.MAX_VALUE))
);
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDCB, EmpClearButton, EmpEmail, EmpFNameText, EmpLNameText, EmpPass, EmpPassConfirm, EmpSubmitButton, EmpTypeCB});
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDLbl, EmpFNameLbl, EmpLNameLbl, EmpSearchButton, EmpTypeLbl, jLabel1, jLabel3, jLabel4});
EmployeeInfoPanelLayout.setVerticalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(EmpOrderLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EMPIDLbl)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpFNameLbl)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel1)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmpSubmitButton)
.addComponent(EmpClearButton)
.addComponent(EmpSearchButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpSearchLbl))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(EmpActiveOrderLbl1)))
.addContainerGap(217, Short.MAX_VALUE))
);
WSCInterface.addTab("Employee Info", EmployeeInfoPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 789, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("");
}// </editor-fold>//GEN-END:initComponents
/* Brad Clawson: These class objects are created to represent the global objects
* that are passed between the tabs in the GUI -
*/
private Employee login = new Employee();
private Customer workingCustomer = new Customer();
private Order workingOrder = new Order();
private OrderVerify workingOV = null;
private QAReport workingQA = new QAReport();
private InventoryItem workingII = new InventoryItem();
public void HideEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Hide password employee fields by default">
EmpPass.setVisible(false);
EmpPassConfirm.setVisible(false);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
// </editor-fold>
}
public void ShowEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Show password employee fields by default">
EmpPass.setVisible(true);
EmpPassConfirm.setVisible(true);
jLabel3.setVisible(true);
jLabel4.setVisible(true);
// </editor-fold>
}
private void setOrderNumberCBModel(ArrayList<Order> orders) {
this.OrderNumberCB.removeAllItems();
for (Order o : orders) {
this.OrderNumberCB.addItem(o);
}
}
private void populateOrderTab(Order order) {
// Media Type Radio Buttons
if (order.getMediaType() != null) {
switch (order.getMediaType().toLowerCase()) {
case "trophy":
this.OrderTypeTrophyRB.setSelected(true);
break;
case "plaque":
this.OrderTypePlaqueRB.setSelected(true);
break;
case "shirt":
this.OrderTypeShirtRB.setSelected(true);
break;
default:
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
}
}
// Set OrderTotalText
this.OrderTotalText.setText(String.format("%.2f", order.getTotal()));
// Set OrderDepositText
this.OrderDepositText.setText(String.format("%.2f", order.getDeposit()));
// Set Accout Payment Radio button
if (order.getPaymentOnAccount())
this.OrderAccountPayRB.setSelected(true);
else if (!order.getPaymentOnAccount())
this.OrderDeliverPayRB.setSelected(true);
// Set Order Status CB
this.OrderStatusCB.removeAllItems();
for (Order.OrderStatus os : Order.OrderStatus.values())
this.OrderStatusCB.addItem(os.toString());
this.OrderStatusCB.setSelectedItem(order.getOrderStatus());
// Set the MediaStatusCB
this.OrderMediaStatusCB.removeAllItems();
for (Order.MediaStatus ms : Order.MediaStatus.values())
this.OrderMediaStatusCB.addItem(order.getMediaStatus());
this.OrderMediaStatusCB.setSelectedItem(order.getMediaStatus());
// Set Content Text
this.OrderContentText.setText(order.getContent());
this.OrderContentText.setEditable(true);
}
private void selectOrderByIndex(int index) {
Order order = (Order)this.OrderNumberCB.getItemAt(index);
this.populateOrderTab(order);
}
private void CustStateCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustStateCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_CustStateCBActionPerformed
private void CustClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustClearButtonActionPerformed
//Clear all fields on customer info
CustClear();
}//GEN-LAST:event_CustClearButtonActionPerformed
public void CustClear() {
//Jacob: Created clear method as it will need called once the customer is created.
CUSTIDCB.setText("");
CustFNameText.setText("");
CustLNameText.setText("");
CustOrgText.setText("");
CustStreet1Text.setText("");
CustStreet2Text.setText("");
CustCityText.setText("");
CustZipText.setText("");
CustPhoneText.setText("");
CustEmailText.setText("");
CustStateCB.setSelectedIndex(0);
custOrdLst.setListData(new Object[0]);
}
private void CustCreateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustCreateButtonActionPerformed
//Jacob: Added Try and Catch to check if parse was successful
//if not through a message explaining
boolean CustExist = false;
String temp;
try{
//Get address and assign an empty string if it doesnt exist
if ("".equals(CustStreet1Text.getText()))
{
temp = "";
}
else
{
temp = CustStreet1Text.getText();
}
//Check if customer exists
CustExist = Customer.isCustomer(Integer.parseInt(CUSTIDCB.getText()),temp);
//If the customer doesnt exist create them else cust already exists update
if (CustExist == false)
{
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.createCust(customer);
JOptionPane.showMessageDialog(null, "Customer created successfully.");
// CustClear();
}
else
{
//Update the customer
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.updateBy(customer);
JOptionPane.showMessageDialog(null, "Customer updated.");
// CustClear();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "A numeric value is required for the following:\nCustomer ID\nCustomer Zip\nCustomer Phone Number", "Numeric Value Required", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Customer was not created.");
}
}//GEN-LAST:event_CustCreateButtonActionPerformed
private void CustFindButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustFindButtonActionPerformed
Customer searchCust = null;
ArrayList<String> cust = new ArrayList<String>();
//Search input to specify column to seach
// <editor-fold defaultstate="collapsed" desc="Get Query for cust search">
if (!"".equals(CUSTIDCB.getText()))
{
searchCust = Customer.searchBy("CUSTID", CUSTIDCB.getText());
}
if (!"".equals(CustFNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustFirstName", CustFNameText.getText());
}
if (!"".equals(CustLNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustLastName", CustLNameText.getText());
}
if (!"".equals(CustOrgText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustOrg", CustOrgText.getText());
}
if (!"".equals(CustStreet1Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet1", CustStreet1Text.getText());
}
if (!"".equals(CustStreet2Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet2", CustStreet2Text.getText());
}
if (!"".equals(CustPhoneText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustPhone", CustPhoneText.getText());
}
//Check if searchCust is null, if not set the customer information
if (searchCust == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
// <editor-fold defaultstate="collapsed" desc="Set customer data to tab">
CUSTIDCB.setText(String.valueOf(searchCust.getCustId()));
CustFNameText.setText(searchCust.getCustFName());
CustLNameText.setText(searchCust.getCustLName());
CustStreet1Text.setText(searchCust.getCustStreet1());
CustStreet2Text.setText(searchCust.getCustStreet2());
CustCityText.setText(searchCust.getCustCity());
CustZipText.setText(String.valueOf(searchCust.getCustZip()));
CustPhoneText.setText(String.valueOf(searchCust.getCustPhone()));
CustEmailText.setText(searchCust.getCustEmail());
CustStateCB.setSelectedItem(searchCust.getCustState());
CustOrgText.setText(searchCust.getCustOrg());
cust = Customer.getOrders(Long.parseLong(CUSTIDCB.getText()));
custOrdLst.setListData(cust.toArray());
// </editor-fold>
}
// </editor-fold>
}//GEN-LAST:event_CustFindButtonActionPerformed
private void LoginPassTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginPassTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginPassTextActionPerformed
private void LoginEMPIDTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginEMPIDTxtActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginEMPIDTxtActionPerformed
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
Login.processLogin(LoginEMPIDTxt.getText(), LoginPassText.getText());
// SetAccessLevel();
}//GEN-LAST:event_LoginButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA Search,Submit,Clear Buttons">
private void QASubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* QAReport object to QAReport.insertOrUpdateQA() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the QAIDText field
* to populate the screen with the information that is searched for and
* verified by the popQA() method. If popQA() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean contentCheck = false, mediaCheck = false, mediaFinishCheck = false,
workmanshipCheck = false, depositCheck = false;
String contentComment = "", mediaComment = "", mediaFinishComment = "",
workmanshipComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if QA check fails
if(QAContentCheckPassRb.isSelected()){
contentCheck = Boolean.TRUE;
}
else if(QAContentCheckFailRb.isSelected()){
contentCheck = Boolean.FALSE;
contentComment = QAContentFailText.getText();
}
if(QAMediaCheckPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(QAMediaCheckFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = QAMediaFailText.getText();
}
if(QAMediaFinishCheckPassRb.isSelected()){
mediaFinishCheck = Boolean.TRUE;
}
else if(QAMediaFinishCheckFailRb.isSelected()){
mediaFinishCheck = Boolean.FALSE;
mediaFinishComment = QAMediaFailText.getText();
}
if(QAWorkmanshipCheckPassRb.isSelected()){
workmanshipCheck = (Boolean.TRUE);
}
else if(QAWorkmanshipCheckFailRb.isSelected()){
workmanshipCheck = (Boolean.FALSE);
workmanshipComment = (QAWorkmanshipFailText.getText());
}
if(QAContentCheckFailRb.isSelected()||
QAMediaCheckFailRb.isSelected()||
QAMediaFinishCheckFailRb.isSelected()||
QAWorkmanshipCheckFailRb.isSelected()){
correctiveActionComment = (QACorrectiveActionText.getText());
}
//Create new QAReport object with screen data to be passed to insertOrUpdateQA()
QAReport newQA = new QAReport((Integer.parseInt(QAIDText.getText())),
Order.getOrder(Integer.parseInt(QAOrderIDText.getText())),
Login.emp, contentCheck, mediaCheck, mediaFinishCheck,
workmanshipCheck, contentComment, mediaComment, mediaFinishComment,
workmanshipComment, correctiveActionComment);
//Object that is returned verifies that the object was created
newQA = QAReport.insertOrUpdateQA(newQA);
//prepare the screen for popQA;
QAIDText.setText(String.valueOf(newQA.getQAID()));
QAOrderIDText.setText("");
//Object is verified a second time through popQA and QAbuttonLbl informs results
if(popQA()){
QAButtonLbl.setText("Create/Update Successful");}
else {
QAButtonLbl.setText("Create/Update Unsuccessful");
}
}//GEN-LAST:event_QASubmitButtonActionPerformed
private void QAClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAClearButtonActionPerformed
//Brad Clawson: Clear information entered into QA tab
QAIDText.setText("");
QAOrderIDText.setText("");
QAContentFailText.setText("");
QAMediaFailText.setText("");
QAMediaFinishFailText.setText("");
QAWorkmanshipFailText.setText("");
QACorrectiveActionText.setText("");
QAContentBG.clearSelection();
QAMediaBG.clearSelection();
QAMediaFinishBG.clearSelection();
QAWorkmanshipBG.clearSelection();
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}//GEN-LAST:event_QAClearButtonActionPerformed
private void QASearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASearchButtonActionPerformed
//Brad Clawson: This method calls the popQA() method to populate the tab
if(popQA()){
QAButtonLbl.setText("Record Found");
}
else{
QAButtonLbl.setText(QAButtonLbl.getText() + ".\n"+"Record Not Found");
}
}//GEN-LAST:event_QASearchButtonActionPerformed
private Boolean popQA(){
/*
* Brad Clawson: Populates Quality Assurance tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND QAID is null or empty search by OrderID
if ((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("ORDERID", Integer.parseInt(QAOrderIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF QAID is not null or empty AND OrderID is null or empty search by QAID
else if ((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("QAID", Integer.parseInt(QAIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF OrderID and QAID are null or empty, notify user to enter proper search criteria
else if((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Please enter a search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//IF OrderID and QAID both not null or empty, notify user to enter single search criteria
else if((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Use a single search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//fill tab content with values from QAReport that was returned in search
QAOrderIDText.setText(String.valueOf(workingQA.getOrder().getORDID()));
QAIDText.setText(String.valueOf(workingQA.getQAID()));
//select correct radio boxes and set fail comments editable or ineditable
if(workingQA.getContentCheck()){
QAContentCheckPassRb.setSelected(true);
QAContentFailText.setEditable(false);}
else if(!workingQA.getContentCheck()){
QAContentCheckFailRb.setSelected(true);
QAContentFailText.setText(workingQA.getContentFailComment());
QAContentFailText.setEditable(true);}
if(workingQA.getMediaCheck()){
QAMediaCheckPassRb.setSelected(true);
QAMediaFailText.setEditable(false);}
else if(!workingQA.getMediaCheck()){
QAMediaCheckFailRb.setSelected(true);
QAMediaFailText.setText(workingQA.getMediaFailComment());
QAMediaFailText.setEditable(true);}
if(workingQA.getMediaFinishCheck()){
QAMediaFinishCheckPassRb.setSelected(true);
QAMediaFinishFailText.setEditable(false);}
else if(!workingQA.getMediaFinishCheck()){
QAMediaFinishCheckFailRb.setSelected(true);
QAMediaFinishFailText.setText(workingQA.getMediaFinishFailComment());
QAMediaFinishFailText.setEditable(true);}
if(workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckPassRb.setSelected(true);
QAWorkmanshipFailText.setEditable(false);}
else if(!workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckFailRb.setSelected(true);
QAWorkmanshipFailText.setText(workingQA.getWorkmanshipFailComment());
QAWorkmanshipFailText.setEditable(true);}
//page successfully populated return true to indicate success
return true;
}
private void QAOrderIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad:reset background color if changed from invalid search param
QAOrderIDText.setBackground(Color.white);
}
private void QAIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad: reset background color if changed from invalid search param
QAIDText.setBackground(Color.white);
}
//</editor-fold>
private void OrderClearFieldsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderClearFieldsButtonActionPerformed
this.OrderCUSTIDText.setText("");
this.OrderNumberCB.removeAllItems();
this.OrderMediaCatNumText.setText("");
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTotalText.setText("");
this.OrderAccountPayRB.setSelected(false);
this.OrderDeliverPayRB.setSelected(false);
this.OrderDepositText.setText("");
this.OrderStatusCB.setSelectedIndex(0);
this.OrderMediaStatusCB.setSelectedIndex(0);
this.OrderContentText.setText("");
}//GEN-LAST:event_OrderClearFieldsButtonActionPerformed
private void OrderCreateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderCreateBtnActionPerformed
Customer cust = Customer.searchBy("CUSTID", "1");
String content = this.OrderContentText.getText();
boolean onAcct = false;
String mediaType = "";
if (this.OrderTypePlaqueRB.isSelected())
mediaType = "plaque";
else if (this.OrderTypeShirtRB.isSelected())
mediaType = "shirt";
else if (this.OrderTypeTrophyRB.isSelected())
mediaType = "trophy";
if (this.OrderAccountPayRB.isSelected())
onAcct = true;
float total = Float.parseFloat(this.OrderTotalText.getText());
float deposit = Float.parseFloat(this.OrderDepositText.getText());
String orderStatus = (String)this.OrderStatusCB.getSelectedItem();
String mediaStatus = (String)this.OrderMediaStatusCB.getSelectedItem();
Employee employee;
if (Login.emp != null)
employee = Login.emp;
else
employee = Employee.searchBy(1);
// Create new Order obj
Order order = new Order(cust, 0, mediaType, content, onAcct, total, deposit, orderStatus, mediaStatus, employee);
order = Order.createOrder(order); // Put into DB
this.populateOrderTab(order); // Populate view from the created obj (see errors this way)
}//GEN-LAST:event_OrderCreateBtnActionPerformed
private void OrderSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderSearchButtonActionPerformed
if (this.OrderCUSTIDText.getText().length() > 0) {
this.orders = Order.getOrders(Integer.parseInt(this.OrderCUSTIDText.getText()));
this.setOrderNumberCBModel(orders);
this.selectOrderByIndex(0);
}
else {
JOptionPane.showMessageDialog(null, "Please search by Customer ID", "Error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_OrderSearchButtonActionPerformed
private void LogoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutButtonActionPerformed
Login.processLogout();
/* //Brad: make all tabs except login invisible Login action will set user access
CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/
}//GEN-LAST:event_LogoutButtonActionPerformed
private void EmpSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSearchButtonActionPerformed
// TODO add your handling code here:
Employee emp = null;
ArrayList<String> orders = new ArrayList<String>();
if (!"".equals(EMPIDCB.getText()))
{
emp = Employee.searchBy(Long.parseLong(EMPIDCB.getText()));
orders = Employee.getOrders(Long.parseLong(EMPIDCB.getText()));
emOrdersLst.setListData(orders.toArray());
}
if (emp == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
EMPIDCB.setText(String.valueOf(emp.getEmpId()));
EmpFNameText.setText(emp.getFirstName());
EmpLNameText.setText(emp.getLastName());
EmpEmail.setText(emp.getEmail());
EmpTypeCB.setSelectedItem(emp.getEmpType());
ShowEmpPassword();
}
}//GEN-LAST:event_EmpSearchButtonActionPerformed
private void EmpSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSubmitButtonActionPerformed
boolean empExist = false;
boolean empUser = false;
String temp;
try{
//Check if employee exists
empExist = Employee.isEmployee(Long.parseLong(EMPIDCB.getText()));
//If the employee doesn't exist create them else employee already exists update
if (empExist == false)
{
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.createEmp(emp);
JOptionPane.showMessageDialog(null, "Employee created successfully.");
//EmpClear();
HideEmpPassword();
}
else
{
String passText = new String(EmpPass.getPassword());
String passTextConfirm = new String(EmpPassConfirm.getPassword());
if (!passText.equals(passTextConfirm))
{
JOptionPane.showMessageDialog(null, "Employee password does not match.");
}
else
{
//Update the employee
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateBy(emp);
emp = null;
empUser = Employee.empUserExist(Long.parseLong(EMPIDCB.getText()));
if (empUser == false)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.addUserLogin(emp);
}
if (empUser == true)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateUserLogin(emp);
}
JOptionPane.showMessageDialog(null, "Employee updated.");
//EmpClear();
HideEmpPassword();
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Employee was not created.");
}
}//GEN-LAST:event_EmpSubmitButtonActionPerformed
public void EmpClear(){
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpTypeCB.setSelectedIndex(0);
}
private void EmpClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpClearButtonActionPerformed
// Clear Employee data
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpPass.setText("");
EmpPassConfirm.setText("");
EmpTypeCB.setSelectedIndex(0);
emOrdersLst.setListData(new Object[0]);
}//GEN-LAST:event_EmpClearButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA radio buttons">
private void QAContentCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAContentFailText.setEditable(false);
}//GEN-LAST:event_QAContentCheckPassRbActionPerformed
private void QAMediaCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFailText.setEditable(false);
}//GEN-LAST:event_QAMediaCheckPassRbActionPerformed
private void QAMediaFinishCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFinishFailText.setEditable(false);
}//GEN-LAST:event_QAMediaFinishCheckPassRbActionPerformed
private void QAWorkmanshipCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAWorkmanshipFailText.setEditable(false);
}//GEN-LAST:event_QAWorkmanshipCheckPassRbActionPerformed
private void QAContentCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAContentFailText.setEditable(true);
}//GEN-LAST:event_QAContentCheckFailRbActionPerformed
private void QAMediaCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFailText.setEditable(true);
}//GEN-LAST:event_QAMediaCheckFailRbActionPerformed
private void QAMediaFinishCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFinishFailText.setEditable(true);
}//GEN-LAST:event_QAMediaFinishCheckFailRbActionPerformed
private void QAWorkmanshipCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAWorkmanshipFailText.setEditable(true);
}//GEN-LAST:event_QAWorkmanshipCheckFailRbActionPerformed
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: OV radio buttons">
private void OVPayTypePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVPayTypePassRb.isSelected()){
OVPayTypeFailText.setEditable(false);
}
}//GEN-LAST:event_OVPayTypePassRbActionPerformed
private void OVPayTypeFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypeFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVPayTypeFailRb.isSelected()){
OVPayTypeFailText.setEditable(true);
}
}//GEN-LAST:event_OVPayTypeFailRbActionPerformed
private void OVDepositFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVDepositFailRb.isSelected()){
OVDepositFailText.setEditable(true);
}
}//GEN-LAST:event_OVDepositFailRbActionPerformed
private void OVDepositPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVDepositPassRb.isSelected()){
OVDepositFailText.setEditable(false);
}
}//GEN-LAST:event_OVDepositPassRbActionPerformed
private void OVContentFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVContentFailRb.isSelected()){
OVContentFailText.setEditable(true);
}
}//GEN-LAST:event_OVContentFailRbActionPerformed
private void OVMediaNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVMediaNumFailRb.isSelected()){
OVMediaFailText.setEditable(true);
}
}//GEN-LAST:event_OVMediaNumFailRbActionPerformed
private void OVAcctNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVAcctNumFailRb.isSelected()){
OVAcctNumFailText.setEditable(true);
}
}//GEN-LAST:event_OVAcctNumFailRbActionPerformed
private void OVCorrectNameFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNameFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVCorrectNameFailRb.isSelected()){
OVNameFailText.setEditable(true);
}
}//GEN-LAST:event_OVCorrectNameFailRbActionPerformed
private void OVContentPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVContentPassRb.isSelected()){
OVContentFailText.setEditable(false);
}
}//GEN-LAST:event_OVContentPassRbActionPerformed
private void OVMediaNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVMediaNumPassRb.isSelected()){
OVMediaFailText.setEditable(false);
}
}//GEN-LAST:event_OVMediaNumPassRbActionPerformed
private void OVAcctNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVAcctNumPassRb.isSelected()){
OVAcctNumFailText.setEditable(false);
}
}//GEN-LAST:event_OVAcctNumPassRbActionPerformed
private void OVCorrectNamePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNamePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVCorrectNamePassRb.isSelected()){
OVNameFailText.setEditable(false);
}
}//GEN-LAST:event_OVCorrectNamePassRbActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Brad Clawson: OV Search,Submit,Clear Buttons">
private void OVSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSearchButtonActionPerformed
//Brad Clawson: search by OVID or OrderID through popID() and indicate success or failure
if(popOV()){
OVButtonLbl.setText("Record Found");
}
else{
OVButtonLbl.setText(OVButtonLbl.getText()+ ". Record not Found");
}
}//GEN-LAST:event_OVSearchButtonActionPerformed
private Boolean popOV(){
/*
* Brad Clawson: Populates Order Verify tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND OVID is null or empty search by OrderID
if ((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("ORDERID", Integer.parseInt(OVOrderIDText.getText()));
}
//IF OVID is not null or empty AND OrderID is null or empty search by OVID
else if ((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("VERID", Integer.parseInt(OVerIDText.getText()));
}
//If both OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Please enter a Order ID or Verification ID for Search");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
//If neither OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Use Only One Field for Searches");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
// make Order information available for easy evaluation
OVCustNameValLbl.setVisible(true);
OVCustIDValLbl.setVisible(true);
OVMediaCatValLbl.setVisible(true);
OVContentValLbl.setVisible(true);
OVPayTypeValLbl.setVisible(true);
OVDepositValLbl.setVisible(true);
OVOrderIDText.setText(String.valueOf(workingOV.getOrder().getORDID()));
OVerIDText.setText(String.valueOf(workingOV.getVerId()));
OVCustNameValLbl.setText(workingOV.getOrder().getCustomer().getCustFName()
+ " " + workingOV.getOrder().getCustomer().getCustLName());
OVCustIDValLbl.setText(String.valueOf(workingOV.getOrder().getCustomer().getCustId()));
// OVMedCatValLbl.setText(String.valueOf(workingOV.getOrder().getMedia().getItemID));
OVContentValLbl.setText("(Content)");
OVContentValLbl.setForeground(Color.BLUE);
//set screen values for returned OrderVerify object
if (workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Account");
}
if (!workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Delivery");
}
OVDepositValLbl.setText(String.valueOf(workingOV.getOrder().getDeposit()));
// OVAssignEmpCB
//set radio button values and set fail comments editable or ineditable
if(workingOV.getNameCheck()){
OVCorrectNamePassRb.setSelected(true);
OVNameFailText.setEditable(false);}
else if(!workingOV.getNameCheck()){
OVCorrectNameFailRb.setSelected(true);
OVNameFailText.setText(workingOV.getNameFailComment());
OVNameFailText.setEditable(true);}
if(workingOV.getAccountCheck()){
OVAcctNumPassRb.setSelected(true);
OVAcctNumFailText.setEditable(false);}
else if(!workingOV.getAccountCheck()){
OVAcctNumFailRb.setSelected(true);
OVAcctNumFailText.setText(workingOV.getAccountFailComment());
OVAcctNumFailText.setEditable(true);}
if(workingOV.getMediaCheck()){
OVMediaNumPassRb.setSelected(true);
OVMediaFailText.setEditable(false);}
else if(!workingOV.getMediaCheck()){
OVMediaNumFailRb.setSelected(true);
OVMediaFailText.setText(workingOV.getMediaFailComment());
OVMediaFailText.setEditable(true);}
if(workingOV.getContentCheck()){
OVContentPassRb.setSelected(true);
OVContentFailText.setEditable(false);}
else if(!workingOV.getContentCheck()){
OVContentFailRb.setSelected(true);
OVContentFailText.setText(workingOV.getContentFailComment());
OVContentFailText.setEditable(true);}
if(workingOV.getPaymentCheck()){
OVPayTypePassRb.setSelected(true);
OVPayTypeFailText.setEditable(false);}
else if(!workingOV.getPaymentCheck()){
OVPayTypeFailRb.setSelected(true);
OVPayTypeFailText.setText(workingOV.getPaymentFailComment());
OVPayTypeFailText.setEditable(true);}
if(workingOV.getDepositCheck()){
OVDepositPassRb.setSelected(true);
OVDepositFailText.setEditable(false);}
else if(!workingOV.getDepositCheck()){
OVDepositFailRb.setSelected(true);
OVDepositFailText.setText(workingOV.getDepositFailComment());
OVDepositFailText.setEditable(true);}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected())
{
OVCommentsText.setText(workingOV.getCorrectiveActionComment());
OVCommentsText.setEditable(true);
}
//tab items successfully populated, return true for success
return true;
}
private void OVClearFieldButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVClearFieldButtonActionPerformed
//Brad Clawson: reset all values on OV tab
OVCustNameValLbl.setText("");
OVCustIDValLbl.setText("");
OVMediaCatValLbl.setText("");
OVContentValLbl.setText("");
OVPayTypeValLbl.setText("");
OVDepositValLbl.setText("");
// OVAssignEmpCB.setText("");
OVOrderIDText.setText("");
OVerIDText.setText("");
OVNameBG.clearSelection();
OVAccountBG.clearSelection();
OVPaymentBG.clearSelection();
OVDepositBG.clearSelection();
OVContentBG.clearSelection();
OVMediaBG.clearSelection();
OVNameFailText.setText("");
OVAcctNumFailText.setText("");
OVMediaFailText.setText("");
OVContentFailText.setText("");
OVPayTypeFailText.setText("");
OVDepositFailText.setText("");
OVCommentsText.setText("");
OVCustNameValLbl.setVisible(false);
OVCustIDValLbl.setVisible(false);
OVMediaCatValLbl.setVisible(false);
OVContentValLbl.setVisible(false);
OVPayTypeValLbl.setVisible(false);
OVDepositValLbl.setVisible(false);
}//GEN-LAST:event_OVClearFieldButtonActionPerformed
private void OVSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* OrderVerify object to OrderVerify.insertOrUpdateOV() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the OVIDText field
* to populate the screen with the information that is searched for and
* verified by the popOV() method. If popOV() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean nameCheck = false, accountCheck = false, mediaCheck = false,
contentCheck = false,paymentCheck = false, depositCheck = false;
String nameComment = "", accountComment = "", mediaComment = "",
contentComment = "", paymentComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if OV check fails
if(OVCorrectNamePassRb.isSelected()){
nameCheck = Boolean.TRUE;
}
else if(OVCorrectNameFailRb.isSelected()){
nameCheck = Boolean.FALSE;
nameComment = OVNameFailText.getText();
}
if(OVAcctNumPassRb.isSelected()){
accountCheck = Boolean.TRUE;
}
else if(OVAcctNumFailRb.isSelected()){
accountCheck = Boolean.FALSE;
accountComment = OVAcctNumFailText.getText();
}
if(OVMediaNumPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(OVMediaNumFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = OVMediaFailText.getText();
}
if(OVContentPassRb.isSelected()){
contentCheck = (Boolean.TRUE);
}
else if(OVContentFailRb.isSelected()){
contentCheck = (Boolean.FALSE);
contentComment = (OVContentFailText.getText());
}
if(OVPayTypePassRb.isSelected()){
paymentCheck = (Boolean.TRUE);
}
else if(OVPayTypeFailRb.isSelected()){
paymentCheck = (Boolean.FALSE);
paymentComment = (OVPayTypeFailText.getText());
}
if (OVDepositPassRb.isSelected()){
depositCheck = (Boolean.TRUE);
}
else if(OVDepositFailRb.isSelected()){
depositCheck = (Boolean.FALSE);
depositComment = (OVDepositFailText.getText());
}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected()){
correctiveActionComment = (OVCommentsText.getText());
}
//Create new OV object with screen data to be passed to insertOrUpdateOV()
OrderVerify newOV = new OrderVerify((Integer.parseInt(OVerIDText.getText())),Login.emp,
Order.getOrder(Integer.parseInt(OVOrderIDText.getText())),
nameCheck, accountCheck, mediaCheck, contentCheck, paymentCheck,
depositCheck, nameComment, accountComment, mediaComment, contentComment,
paymentComment, depositComment,correctiveActionComment);
//Object that is returned verifies that the object was created
newOV = OrderVerify.insertOrUpdateOV(newOV);
//prepare screen for popOV()
OVerIDText.setText(String.valueOf(newOV.getVerId()));
OVOrderIDText.setText("");
//Record is searched for and verified a second time through popOV()
if(popOV()){
OVButtonLbl.setText("Create/Update Successful");}
}//GEN-LAST:event_OVSubmitButtonActionPerformed
//</editor-fold>
private void OrderStatusCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderStatusCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_OrderStatusCBActionPerformed
private void emOrdersLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_emOrdersLstValueChanged
// TODO add your handling code here:
}//GEN-LAST:event_emOrdersLstValueChanged
private void custOrdLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_custOrdLstValueChanged
//Add code for customer orders
}//GEN-LAST:event_custOrdLstValueChanged
private void EmpTypeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpTypeCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_EmpTypeCBActionPerformed
private void OrderNumberCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderNumberCBActionPerformed
if (this.OrderNumberCB.getSelectedIndex() != -1)
this.selectOrderByIndex(this.OrderNumberCB.getSelectedIndex());
}//GEN-LAST:event_OrderNumberCBActionPerformed
private void OrderUpdateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void OVContentValLblMouseClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OVContentValLblMouseClick
//Brad: popup content in JOption pane for easy access when verifying order
JOptionPane.showMessageDialog(null, workingOV.getOrder().getContent());
}//GEN-LAST:event_OVContentValLblMouseClick
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: InventoryItem Search,Submit,Clear Buttons">
private void InvClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvClearButtonActionPerformed
// Clear Inventory data
InvItemIdText.setText("");
InvManufacturerIdText.setText("");
InvItemNameText.setText("");
InvOnHandText.setText("");
InvOnOrderText.setText("");
InvDeliveryDateText.setText("");
}//GEN-LAST:event_InvClearButtonActionPerformed
private void InvOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvOrderButtonActionPerformed
}//GEN-LAST:event_InvOrderButtonActionPerformed
private void InvSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvSearchButtonActionPerformed
if(popII()){
InvButtonLbl.setText("Item(s) found");
}
}//GEN-LAST:event_InvSearchButtonActionPerformed
private Boolean popII(){ /*
* Brad Clawson: Populates Inventory Item tab by searching either ItemID Number,
* Manufacturer, or name but not by more than one field.
*/
//search by ITEMID if ManID and ItemName are null or empty
if ((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("ITEMID", InvItemIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by MANID if ITEMID and ItemName are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("MANID", InvManufacturerIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by ItemName if ManID and ITEMID are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("Name", InvItemNameText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//if search criteria are all null or empty, return false with notification
else if((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Please enter a search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
InvItemNameText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
|| (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//populate Inventory Item Tab fields
InvItemIdText.setText(String.valueOf(workingII.getItemNumber()));
InvManufacturerIdText.setText(String.valueOf(workingII.getManufacturerID()));
InvItemNameText.setText(workingII.getName());
InvOnHandText.setText(String.valueOf(workingII.getQtyOnHand()));
InvOnOrderText.setText(String.valueOf(workingII.getQtyOnOrder()));
InvDeliveryDateText.setText(workingII.getDeliveryDate());
return true;
}
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="GUI Variable Declarations">
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField CUSTIDCB;
private javax.swing.JLabel CUSTIDLbl;
private javax.swing.JLabel CustActiveOrderLbl;
private javax.swing.JLabel CustCityLbl;
private javax.swing.JTextField CustCityText;
private javax.swing.JButton CustClearButton;
private javax.swing.JButton CustCreateButton;
private javax.swing.JLabel CustEmailLbl;
private javax.swing.JTextField CustEmailText;
private javax.swing.JLabel CustFNameLbl;
private javax.swing.JTextField CustFNameText;
private javax.swing.JButton CustFindButton;
private javax.swing.JLabel CustLNameLbl;
private javax.swing.JTextField CustLNameText;
private javax.swing.JScrollPane CustOrderListBox;
private javax.swing.JLabel CustOrderListBoxLbl;
private javax.swing.JLabel CustOrgLbl;
private javax.swing.JTextField CustOrgText;
private javax.swing.JLabel CustPhoneLbl;
private javax.swing.JTextField CustPhoneText;
private javax.swing.JComboBox CustStateCB;
private javax.swing.JLabel CustStateLbl;
private javax.swing.JLabel CustStreet1Lbl;
private javax.swing.JTextField CustStreet1Text;
private javax.swing.JLabel CustStreet2Lbl;
private javax.swing.JTextField CustStreet2Text;
private javax.swing.JLabel CustZipLbl;
private javax.swing.JTextField CustZipText;
private javax.swing.JPanel CustomerInfoPanel;
private javax.swing.JTextField EMPIDCB;
private javax.swing.JLabel EMPIDLbl;
private javax.swing.JLabel EmpActiveOrderLbl1;
private javax.swing.JButton EmpClearButton;
private javax.swing.JTextField EmpEmail;
private javax.swing.JLabel EmpFNameLbl;
private javax.swing.JTextField EmpFNameText;
private javax.swing.JLabel EmpLNameLbl;
private javax.swing.JTextField EmpLNameText;
private javax.swing.JScrollPane EmpOrderLB;
private javax.swing.JLabel EmpOrderLbl;
private javax.swing.JPasswordField EmpPass;
private javax.swing.JPasswordField EmpPassConfirm;
private javax.swing.JButton EmpSearchButton;
private javax.swing.JLabel EmpSearchLbl;
private javax.swing.JButton EmpSubmitButton;
private javax.swing.JComboBox EmpTypeCB;
private javax.swing.JLabel EmpTypeLbl;
private javax.swing.JPanel EmployeeInfoPanel;
private javax.swing.JLabel InvButtonLbl;
private javax.swing.JButton InvClearButton;
private javax.swing.JLabel InvDeliveryDateLbl;
private javax.swing.JTextField InvDeliveryDateText;
private javax.swing.JLabel InvItemIDLbl;
private javax.swing.JTextField InvItemIdText;
private javax.swing.JLabel InvItemNameLbl;
private javax.swing.JTextField InvItemNameText;
private javax.swing.JLabel InvManufacturerIdLbl;
private javax.swing.JTextField InvManufacturerIdText;
private javax.swing.JLabel InvManufacturerItemLbl;
private javax.swing.JList InvManufacturerItemList;
private javax.swing.JScrollPane InvManufacturerItemScrollPane;
private javax.swing.JTextField InvOnHandText;
private javax.swing.JTextField InvOnOrderText;
private javax.swing.JButton InvOrderButton;
private javax.swing.JLabel InvOrderIdLbl;
private javax.swing.JTextField InvOrderIdText;
private javax.swing.JLabel InvQtyOnHandLbl;
private javax.swing.JLabel InvQtyOnOrderLbl;
private javax.swing.JButton InvSearchButton;
private javax.swing.JLabel InvSearchLbl5;
private javax.swing.JPanel InventoryPanel;
private javax.swing.JButton LoginButton;
private javax.swing.JLabel LoginEMPIDLbl;
private javax.swing.JTextField LoginEMPIDTxt;
private javax.swing.JPanel LoginPanel;
private javax.swing.JLabel LoginPassLbl;
private javax.swing.JPasswordField LoginPassText;
private javax.swing.JButton LogoutButton;
private javax.swing.ButtonGroup OVAccountBG;
private javax.swing.JRadioButton OVAcctNumFailRb;
private javax.swing.JTextField OVAcctNumFailText;
private javax.swing.JLabel OVAcctNumLbl;
private javax.swing.JRadioButton OVAcctNumPassRb;
private javax.swing.JComboBox OVAssignEmpCB;
private javax.swing.JLabel OVAssignEmpLbl;
private javax.swing.JLabel OVAssignedToLbl;
private javax.swing.JLabel OVButtonLbl;
private javax.swing.JButton OVClearFieldButton;
private javax.swing.JLabel OVCommentsLbl;
private javax.swing.JScrollPane OVCommentsTB;
private javax.swing.JTextArea OVCommentsText;
private javax.swing.ButtonGroup OVContentBG;
private javax.swing.JRadioButton OVContentFailRb;
private javax.swing.JTextField OVContentFailText;
private javax.swing.JLabel OVContentLbl;
private javax.swing.JRadioButton OVContentPassRb;
private javax.swing.JLabel OVContentValLbl;
private javax.swing.JRadioButton OVCorrectNameFailRb;
private javax.swing.JLabel OVCorrectNameLbl;
private javax.swing.JRadioButton OVCorrectNamePassRb;
private javax.swing.JLabel OVCreateByLbl;
private javax.swing.JLabel OVCustIDValLbl;
private javax.swing.JLabel OVCustNameValLbl;
private javax.swing.ButtonGroup OVDepositBG;
private javax.swing.JRadioButton OVDepositFailRb;
private javax.swing.JTextField OVDepositFailText;
private javax.swing.JLabel OVDepositLbl;
private javax.swing.JRadioButton OVDepositPassRb;
private javax.swing.JLabel OVDepositValLbl;
private javax.swing.JLabel OVFailLbl;
private javax.swing.ButtonGroup OVMediaBG;
private javax.swing.JLabel OVMediaCatValLbl;
private javax.swing.JTextField OVMediaFailText;
private javax.swing.JRadioButton OVMediaNumFailRb;
private javax.swing.JLabel OVMediaNumLbl;
private javax.swing.JRadioButton OVMediaNumPassRb;
private javax.swing.ButtonGroup OVNameBG;
private javax.swing.JTextField OVNameFailText;
private javax.swing.JLabel OVNumberLbl;
private javax.swing.JTextField OVOrderIDText;
private javax.swing.JLabel OVOrderNumLbl;
private javax.swing.JLabel OVPassLbl;
private javax.swing.JRadioButton OVPayTypeFailRb;
private javax.swing.JTextField OVPayTypeFailText;
private javax.swing.JLabel OVPayTypePassLbl;
private javax.swing.JRadioButton OVPayTypePassRb;
private javax.swing.JLabel OVPayTypeValLbl;
private javax.swing.ButtonGroup OVPaymentBG;
private javax.swing.JLabel OVReasonLbl;
private javax.swing.JButton OVSearchButton;
private javax.swing.JButton OVSubmitButton;
private javax.swing.JLabel OVVerifyByLbl;
private javax.swing.JTextField OVerIDText;
private javax.swing.JRadioButton OrderAccountPayRB;
private javax.swing.JLabel OrderAssignedToLbl;
private javax.swing.JTextField OrderCUSTIDText;
private javax.swing.JButton OrderClearFieldsButton;
private javax.swing.JLabel OrderContentLbl;
private javax.swing.JTextField OrderContentText;
private javax.swing.JButton OrderCreateBtn;
private javax.swing.JLabel OrderCreatedByLbl;
private javax.swing.JLabel OrderCustNumberLbl;
private javax.swing.JRadioButton OrderDeliverPayRB;
private javax.swing.JLabel OrderDepositLbl;
private javax.swing.JTextField OrderDepositText;
private javax.swing.ButtonGroup OrderEngMediaBG;
private javax.swing.JPanel OrderInfoPanel;
private javax.swing.JLabel OrderMediaCatNumLbl;
private javax.swing.JTextField OrderMediaCatNumText;
private javax.swing.JComboBox OrderMediaStatusCB;
private javax.swing.JLabel OrderMediaStatusLbl;
private javax.swing.JLabel OrderMediaTypeLbl;
private javax.swing.JComboBox OrderNumberCB;
private javax.swing.JLabel OrderNumberLbl;
private javax.swing.ButtonGroup OrderPayTypeBG;
private javax.swing.JLabel OrderPaymentTypeLbl;
private javax.swing.JButton OrderSearchButton;
private javax.swing.JLabel OrderSearchLbl;
private javax.swing.JComboBox OrderStatusCB;
private javax.swing.JLabel OrderStatusLbl;
private javax.swing.JTabbedPane OrderTabbedPane;
private javax.swing.JLabel OrderTotalLbl;
private javax.swing.JTextField OrderTotalText;
private javax.swing.ButtonGroup OrderTypeBG;
private javax.swing.JRadioButton OrderTypePlaqueRB;
private javax.swing.JRadioButton OrderTypeShirtRB;
private javax.swing.JRadioButton OrderTypeTrophyRB;
private javax.swing.JButton OrderUpdateBtn;
private javax.swing.JLabel OrderVerifyByLbl;
private javax.swing.JPanel OrderVerifyPanel;
private javax.swing.JLabel QAAssignedToLbl;
private javax.swing.JLabel QAButtonLbl;
private javax.swing.JButton QAClearButton;
private javax.swing.JLabel QACommentLbl;
private javax.swing.ButtonGroup QAContentBG;
private javax.swing.JRadioButton QAContentCheckFailRb;
private javax.swing.JRadioButton QAContentCheckPassRb;
private javax.swing.JTextField QAContentFailText;
private javax.swing.JLabel QAContentLbl;
private javax.swing.JScrollPane QACorrectiveActionTB;
private javax.swing.JTextArea QACorrectiveActionText;
private javax.swing.JLabel QACreatedByLbl;
private javax.swing.JLabel QAFailCommentLbl;
private javax.swing.JLabel QAFailLbl;
private javax.swing.JLabel QAIDLbl;
private javax.swing.JTextField QAIDText;
private javax.swing.ButtonGroup QAMediaBG;
private javax.swing.JRadioButton QAMediaCheckFailRb;
private javax.swing.JRadioButton QAMediaCheckPassRb;
private javax.swing.JTextField QAMediaFailText;
private javax.swing.ButtonGroup QAMediaFinishBG;
private javax.swing.JRadioButton QAMediaFinishCheckFailRb;
private javax.swing.JRadioButton QAMediaFinishCheckPassRb;
private javax.swing.JTextField QAMediaFinishFailText;
private javax.swing.JLabel QAMediaFinishLbl;
private javax.swing.JLabel QAMediaLbl;
private javax.swing.JLabel QAOrderIDLbl;
private javax.swing.JTextField QAOrderIDText;
private javax.swing.JPanel QAPanel;
private javax.swing.JLabel QAPassLbl;
private javax.swing.JButton QASearchButton;
private javax.swing.JButton QASubmitButton;
private javax.swing.JLabel QAVerifiedByLbl;
private javax.swing.ButtonGroup QAWorkmanshipBG;
private javax.swing.JRadioButton QAWorkmanshipCheckFailRb;
private javax.swing.JRadioButton QAWorkmanshipCheckPassRb;
private javax.swing.JTextField QAWorkmanshipFailText;
private javax.swing.JLabel QAWorkmanshipLbl;
private javax.swing.JTabbedPane WSCInterface;
private javax.swing.JList custOrdLst;
private javax.swing.JList emOrdersLst;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
protected javax.swing.JLabel lblLoginStatus;
// End of variables declaration//GEN-END:variables
//</editor-fold>
}
| public WilliamsSpecialtyGUI() {
initComponents();
HideEmpPassword();
/* //Brad: make all tabs except login invisible Login action will set user access
* CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/ }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
OrderPayTypeBG = new javax.swing.ButtonGroup();
OrderTypeBG = new javax.swing.ButtonGroup();
OrderEngMediaBG = new javax.swing.ButtonGroup();
OVAccountBG = new javax.swing.ButtonGroup();
OVNameBG = new javax.swing.ButtonGroup();
QAContentBG = new javax.swing.ButtonGroup();
QAMediaBG = new javax.swing.ButtonGroup();
QAMediaFinishBG = new javax.swing.ButtonGroup();
QAWorkmanshipBG = new javax.swing.ButtonGroup();
OVMediaBG = new javax.swing.ButtonGroup();
OVContentBG = new javax.swing.ButtonGroup();
OVPaymentBG = new javax.swing.ButtonGroup();
OVDepositBG = new javax.swing.ButtonGroup();
WSCInterface = new javax.swing.JTabbedPane();
LoginPanel = new javax.swing.JPanel();
LoginButton = new javax.swing.JButton();
LoginEMPIDTxt = new javax.swing.JTextField();
LoginEMPIDLbl = new javax.swing.JLabel();
LoginPassLbl = new javax.swing.JLabel();
LoginPassText = new javax.swing.JPasswordField();
LogoutButton = new javax.swing.JButton();
lblLoginStatus = new javax.swing.JLabel();
CustomerInfoPanel = new javax.swing.JPanel();
CustFNameText = new javax.swing.JTextField();
CustLNameText = new javax.swing.JTextField();
CustOrgText = new javax.swing.JTextField();
CustStreet1Text = new javax.swing.JTextField();
CustStreet2Text = new javax.swing.JTextField();
CustFNameLbl = new javax.swing.JLabel();
CustLNameLbl = new javax.swing.JLabel();
CustOrgLbl = new javax.swing.JLabel();
CustStreet1Lbl = new javax.swing.JLabel();
CustStreet2Lbl = new javax.swing.JLabel();
CustCityText = new javax.swing.JTextField();
CustZipText = new javax.swing.JTextField();
CustCityLbl = new javax.swing.JLabel();
CustZipLbl = new javax.swing.JLabel();
CustFindButton = new javax.swing.JButton();
CustCreateButton = new javax.swing.JButton();
CustOrderListBox = new javax.swing.JScrollPane();
custOrdLst = new javax.swing.JList();
CustOrderListBoxLbl = new javax.swing.JLabel();
CustClearButton = new javax.swing.JButton();
CustActiveOrderLbl = new javax.swing.JLabel();
CUSTIDLbl = new javax.swing.JLabel();
CustStateCB = new javax.swing.JComboBox();
CustStateLbl = new javax.swing.JLabel();
InvSearchLbl5 = new javax.swing.JLabel();
CustPhoneLbl = new javax.swing.JLabel();
CustPhoneText = new javax.swing.JTextField();
CustEmailLbl = new javax.swing.JLabel();
CustEmailText = new javax.swing.JTextField();
CUSTIDCB = new javax.swing.JTextField();
OrderTabbedPane = new javax.swing.JTabbedPane();
OrderInfoPanel = new javax.swing.JPanel();
OrderNumberLbl = new javax.swing.JLabel();
OrderDeliverPayRB = new javax.swing.JRadioButton();
OrderAccountPayRB = new javax.swing.JRadioButton();
OrderDepositLbl = new javax.swing.JLabel();
OrderDepositText = new javax.swing.JTextField();
OrderTypeShirtRB = new javax.swing.JRadioButton();
OrderTypeTrophyRB = new javax.swing.JRadioButton();
OrderTypePlaqueRB = new javax.swing.JRadioButton();
OrderContentLbl = new javax.swing.JLabel();
OrderContentText = new javax.swing.JTextField();
OrderMediaCatNumLbl = new javax.swing.JLabel();
OrderMediaCatNumText = new javax.swing.JTextField();
OrderMediaTypeLbl = new javax.swing.JLabel();
OrderCustNumberLbl = new javax.swing.JLabel();
OrderCUSTIDText = new javax.swing.JTextField();
OrderPaymentTypeLbl = new javax.swing.JLabel();
OrderClearFieldsButton = new javax.swing.JButton();
OrderCreateBtn = new javax.swing.JButton();
OrderSearchButton = new javax.swing.JButton();
OrderMediaStatusCB = new javax.swing.JComboBox();
OrderStatusLbl = new javax.swing.JLabel();
OrderStatusCB = new javax.swing.JComboBox();
OrderMediaStatusLbl = new javax.swing.JLabel();
OrderTotalLbl = new javax.swing.JLabel();
OrderTotalText = new javax.swing.JTextField();
OrderVerifyByLbl = new javax.swing.JLabel();
OrderAssignedToLbl = new javax.swing.JLabel();
OrderCreatedByLbl = new javax.swing.JLabel();
OrderNumberCB = new javax.swing.JComboBox();
OrderSearchLbl = new javax.swing.JLabel();
OrderUpdateBtn = new javax.swing.JButton();
OrderVerifyPanel = new javax.swing.JPanel();
OVSubmitButton = new javax.swing.JButton();
OVClearFieldButton = new javax.swing.JButton();
OVSearchButton = new javax.swing.JButton();
OVCorrectNameLbl = new javax.swing.JLabel();
OVAcctNumLbl = new javax.swing.JLabel();
OVMediaNumLbl = new javax.swing.JLabel();
OVContentLbl = new javax.swing.JLabel();
OVCorrectNamePassRb = new javax.swing.JRadioButton();
OVAcctNumPassRb = new javax.swing.JRadioButton();
OVMediaNumPassRb = new javax.swing.JRadioButton();
OVContentPassRb = new javax.swing.JRadioButton();
OVCorrectNameFailRb = new javax.swing.JRadioButton();
OVAcctNumFailRb = new javax.swing.JRadioButton();
OVMediaNumFailRb = new javax.swing.JRadioButton();
OVContentFailRb = new javax.swing.JRadioButton();
OVCommentsTB = new javax.swing.JScrollPane();
OVCommentsText = new javax.swing.JTextArea();
OVCommentsLbl = new javax.swing.JLabel();
OVNameFailText = new javax.swing.JTextField();
OVAcctNumFailText = new javax.swing.JTextField();
OVMediaFailText = new javax.swing.JTextField();
OVContentFailText = new javax.swing.JTextField();
OVPassLbl = new javax.swing.JLabel();
OVFailLbl = new javax.swing.JLabel();
OVReasonLbl = new javax.swing.JLabel();
OVDepositPassRb = new javax.swing.JRadioButton();
OVDepositLbl = new javax.swing.JLabel();
OVDepositFailRb = new javax.swing.JRadioButton();
OVPayTypeFailRb = new javax.swing.JRadioButton();
OVPayTypePassLbl = new javax.swing.JLabel();
OVDepositFailText = new javax.swing.JTextField();
OVPayTypeFailText = new javax.swing.JTextField();
OVPayTypePassRb = new javax.swing.JRadioButton();
OVNumberLbl = new javax.swing.JLabel();
OVerIDText = new javax.swing.JTextField();
OVCustNameValLbl = new javax.swing.JLabel();
OVCustIDValLbl = new javax.swing.JLabel();
OVMediaCatValLbl = new javax.swing.JLabel();
OVContentValLbl = new javax.swing.JLabel();
OVPayTypeValLbl = new javax.swing.JLabel();
OVDepositValLbl = new javax.swing.JLabel();
OVAssignEmpCB = new javax.swing.JComboBox();
OVAssignEmpLbl = new javax.swing.JLabel();
OVOrderNumLbl = new javax.swing.JLabel();
OVOrderIDText = new javax.swing.JTextField();
OVVerifyByLbl = new javax.swing.JLabel();
OVCreateByLbl = new javax.swing.JLabel();
OVAssignedToLbl = new javax.swing.JLabel();
OVButtonLbl = new javax.swing.JLabel();
QAPanel = new javax.swing.JPanel();
QASubmitButton = new javax.swing.JButton();
QAClearButton = new javax.swing.JButton();
QASearchButton = new javax.swing.JButton();
QAContentLbl = new javax.swing.JLabel();
QAMediaLbl = new javax.swing.JLabel();
QAMediaFinishLbl = new javax.swing.JLabel();
QAWorkmanshipLbl = new javax.swing.JLabel();
QAContentCheckPassRb = new javax.swing.JRadioButton();
QAMediaCheckPassRb = new javax.swing.JRadioButton();
QAMediaFinishCheckPassRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckPassRb = new javax.swing.JRadioButton();
QAContentCheckFailRb = new javax.swing.JRadioButton();
QAMediaCheckFailRb = new javax.swing.JRadioButton();
QAMediaFinishCheckFailRb = new javax.swing.JRadioButton();
QAWorkmanshipCheckFailRb = new javax.swing.JRadioButton();
QACorrectiveActionTB = new javax.swing.JScrollPane();
QACorrectiveActionText = new javax.swing.JTextArea();
QACommentLbl = new javax.swing.JLabel();
QAContentFailText = new javax.swing.JTextField();
QAMediaFailText = new javax.swing.JTextField();
QAMediaFinishFailText = new javax.swing.JTextField();
QAWorkmanshipFailText = new javax.swing.JTextField();
QAPassLbl = new javax.swing.JLabel();
QAFailLbl = new javax.swing.JLabel();
QAFailCommentLbl = new javax.swing.JLabel();
QAVerifiedByLbl = new javax.swing.JLabel();
QACreatedByLbl = new javax.swing.JLabel();
QAAssignedToLbl = new javax.swing.JLabel();
QAOrderIDLbl = new javax.swing.JLabel();
QAIDLbl = new javax.swing.JLabel();
QAButtonLbl = new javax.swing.JLabel();
QAOrderIDText = new javax.swing.JTextField();
QAIDText = new javax.swing.JTextField();
InventoryPanel = new javax.swing.JPanel();
InvItemIDLbl = new javax.swing.JLabel();
InvManufacturerIdLbl = new javax.swing.JLabel();
InvQtyOnHandLbl = new javax.swing.JLabel();
InvQtyOnOrderLbl = new javax.swing.JLabel();
InvDeliveryDateLbl = new javax.swing.JLabel();
InvOrderButton = new javax.swing.JButton();
InvClearButton = new javax.swing.JButton();
InvSearchButton = new javax.swing.JButton();
InvItemNameLbl = new javax.swing.JLabel();
InvItemNameText = new javax.swing.JTextField();
InvButtonLbl = new javax.swing.JLabel();
InvOnHandText = new javax.swing.JTextField();
InvOnOrderText = new javax.swing.JTextField();
InvDeliveryDateText = new javax.swing.JTextField();
InvItemIdText = new javax.swing.JTextField();
InvManufacturerIdText = new javax.swing.JTextField();
InvOrderIdLbl = new javax.swing.JLabel();
InvOrderIdText = new javax.swing.JTextField();
InvManufacturerItemScrollPane = new javax.swing.JScrollPane();
InvManufacturerItemList = new javax.swing.JList();
InvManufacturerItemLbl = new javax.swing.JLabel();
EmployeeInfoPanel = new javax.swing.JPanel();
EmpFNameText = new javax.swing.JTextField();
EmpLNameText = new javax.swing.JTextField();
EmpFNameLbl = new javax.swing.JLabel();
EmpLNameLbl = new javax.swing.JLabel();
EmpSearchButton = new javax.swing.JButton();
EmpSubmitButton = new javax.swing.JButton();
EmpOrderLB = new javax.swing.JScrollPane();
emOrdersLst = new javax.swing.JList();
EmpOrderLbl = new javax.swing.JLabel();
EmpClearButton = new javax.swing.JButton();
EmpActiveOrderLbl1 = new javax.swing.JLabel();
EMPIDLbl = new javax.swing.JLabel();
EmpTypeCB = new javax.swing.JComboBox();
EmpTypeLbl = new javax.swing.JLabel();
EmpSearchLbl = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
EmpEmail = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
EmpPass = new javax.swing.JPasswordField();
jLabel4 = new javax.swing.JLabel();
EmpPassConfirm = new javax.swing.JPasswordField();
EMPIDCB = new javax.swing.JTextField();
setPreferredSize(new java.awt.Dimension(600, 549));
WSCInterface.setPreferredSize(new java.awt.Dimension(600, 549));
LoginPanel.setDoubleBuffered(false);
LoginButton.setText("Login");
LoginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginButtonActionPerformed(evt);
}
});
LoginEMPIDTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginEMPIDTxtActionPerformed(evt);
}
});
LoginEMPIDLbl.setText("Employee ID");
LoginPassLbl.setText("Password");
LoginPassText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginPassTextActionPerformed(evt);
}
});
LogoutButton.setText("Logout");
LogoutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LogoutButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout LoginPanelLayout = new javax.swing.GroupLayout(LoginPanel);
LoginPanel.setLayout(LoginPanelLayout);
LoginPanelLayout.setHorizontalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(260, 260, 260)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, LoginPanelLayout.createSequentialGroup()
.addComponent(LoginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(LogoutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginPassLbl))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LoginEMPIDTxt)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblLoginStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(199, Short.MAX_VALUE))
);
LoginPanelLayout.setVerticalGroup(
LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LoginPanelLayout.createSequentialGroup()
.addGap(157, 157, 157)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginEMPIDLbl)
.addComponent(LoginEMPIDTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LoginPassLbl)
.addComponent(LoginPassText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblLoginStatus))
.addGap(18, 18, 18)
.addGroup(LoginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(LogoutButton)
.addComponent(LoginButton))
.addContainerGap(388, Short.MAX_VALUE))
);
WSCInterface.addTab("Login", LoginPanel);
CustFNameLbl.setText("First Name");
CustLNameLbl.setText("Last Name");
CustOrgLbl.setText("Organization");
CustStreet1Lbl.setText("Street Address Line 1");
CustStreet2Lbl.setText("Street Address Line 2");
CustCityLbl.setText("City");
CustZipLbl.setText("Zip");
CustFindButton.setText("Search");
CustFindButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustFindButtonActionPerformed(evt);
}
});
CustCreateButton.setText("Create/Update");
CustCreateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustCreateButtonActionPerformed(evt);
}
});
custOrdLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
custOrdLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
custOrdLstValueChanged(evt);
}
});
CustOrderListBox.setViewportView(custOrdLst);
CustOrderListBoxLbl.setText("Order(s):");
CustClearButton.setText("Clear Fields");
CustClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustClearButtonActionPerformed(evt);
}
});
CustActiveOrderLbl.setForeground(new java.awt.Color(255, 0, 0));
CustActiveOrderLbl.setText("*Active orders in red");
CUSTIDLbl.setText("Customer Number");
CustStateCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"", "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA",
"ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" }));
CustStateCB.setPreferredSize(new java.awt.Dimension(35, 20));
CustStateCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CustStateCBActionPerformed(evt);
}
});
CustStateLbl.setText("State");
InvSearchLbl5.setForeground(new java.awt.Color(255, 51, 51));
InvSearchLbl5.setText("* Use only one field for searches");
CustPhoneLbl.setText("Phone Number");
CustEmailLbl.setText("Email");
javax.swing.GroupLayout CustomerInfoPanelLayout = new javax.swing.GroupLayout(CustomerInfoPanel);
CustomerInfoPanel.setLayout(CustomerInfoPanelLayout);
CustomerInfoPanelLayout.setHorizontalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustEmailLbl)
.addComponent(InvSearchLbl5)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustPhoneLbl)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustStateLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(CustCityLbl)
.addComponent(CustStreet2Lbl)
.addComponent(CustStreet1Lbl)
.addComponent(CustOrgLbl)
.addComponent(CustFNameLbl)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustZipLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CUSTIDLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustActiveOrderLbl)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrderListBoxLbl)))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustFindButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustCreateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustClearButton)))
.addContainerGap(286, Short.MAX_VALUE))
);
CustomerInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CustCityText, CustEmailText, CustFNameText, CustLNameText, CustOrgText, CustPhoneText, CustStreet1Text, CustStreet2Text, CustZipText});
CustomerInfoPanelLayout.setVerticalGroup(
CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addComponent(CustOrderListBoxLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustOrderListBox, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CustActiveOrderLbl))
.addGroup(CustomerInfoPanelLayout.createSequentialGroup()
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CUSTIDLbl)
.addComponent(CUSTIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustFNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustOrgText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustOrgLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet1Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustStreet2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStreet2Lbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustCityText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustCityLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustZipText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustZipLbl)
.addComponent(CustStateCB, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CustStateLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustPhoneLbl)
.addComponent(CustPhoneText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustEmailLbl)
.addComponent(CustEmailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(CustomerInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustFindButton)
.addComponent(CustCreateButton)
.addComponent(CustClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvSearchLbl5)
.addContainerGap(208, Short.MAX_VALUE))
);
WSCInterface.addTab("Customer Info", CustomerInfoPanel);
OrderNumberLbl.setText("Order Number");
OrderPayTypeBG.add(OrderDeliverPayRB);
OrderDeliverPayRB.setText("Payment on Delivery");
OrderPayTypeBG.add(OrderAccountPayRB);
OrderAccountPayRB.setText("Payment on Account");
OrderDepositLbl.setText("Deposit Amount");
OrderTypeBG.add(OrderTypeShirtRB);
OrderTypeShirtRB.setText("Shirt");
OrderTypeBG.add(OrderTypeTrophyRB);
OrderTypeTrophyRB.setText("Trophy");
OrderTypeBG.add(OrderTypePlaqueRB);
OrderTypePlaqueRB.setText("Plaque");
OrderContentLbl.setText("Printing/Engraving Content:");
OrderMediaCatNumLbl.setText("Media Catalog Number");
OrderMediaTypeLbl.setText("Media Type");
OrderCustNumberLbl.setText("Customer Number");
OrderPaymentTypeLbl.setText("Payment Type");
OrderClearFieldsButton.setText("Clear Fields");
OrderClearFieldsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderClearFieldsButtonActionPerformed(evt);
}
});
OrderCreateBtn.setText("Create");
OrderCreateBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderCreateBtnActionPerformed(evt);
}
});
OrderSearchButton.setText("Search");
OrderSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderSearchButtonActionPerformed(evt);
}
});
OrderMediaStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusLbl.setText("Order Status");
OrderStatusCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OrderStatusCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderStatusCBActionPerformed(evt);
}
});
OrderMediaStatusLbl.setText("Media Status");
OrderTotalLbl.setText("Estimated Total");
OrderVerifyByLbl.setText("Order Verified by ******");
OrderAssignedToLbl.setText("Work Assigned to ******");
OrderCreatedByLbl.setText("Order Created by ******");
OrderNumberCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OrderNumberCBActionPerformed(evt);
}
});
OrderSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
OrderSearchLbl.setText("* Use only one field for searches");
OrderUpdateBtn.setText("Update");
javax.swing.GroupLayout OrderInfoPanelLayout = new javax.swing.GroupLayout(OrderInfoPanel);
OrderInfoPanel.setLayout(OrderInfoPanelLayout);
OrderInfoPanelLayout.setHorizontalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderTypeShirtRB)
.addComponent(OrderTypePlaqueRB)
.addComponent(OrderTypeTrophyRB)
.addComponent(OrderStatusLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderAccountPayRB)
.addComponent(OrderDeliverPayRB)
.addComponent(OrderPaymentTypeLbl)
.addComponent(OrderTotalLbl)
.addComponent(OrderMediaTypeLbl)
.addComponent(OrderMediaCatNumLbl)
.addComponent(OrderNumberLbl)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderInfoPanelLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(OrderMediaStatusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderClearFieldsButton)
.addComponent(OrderUpdateBtn)
.addComponent(OrderCreateBtn)
.addComponent(OrderSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(131, Short.MAX_VALUE))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(215, 215, 215)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OrderVerifyByLbl)
.addComponent(OrderCreatedByLbl))
.addGap(48, 48, 48)
.addComponent(OrderAssignedToLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(OrderDepositLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(371, 371, 371)
.addComponent(OrderSearchLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(331, 331, 331)
.addComponent(OrderContentLbl)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderNumberCB, OrderStatusCB, OrderTotalText});
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OrderClearFieldsButton, OrderCreateBtn, OrderSearchButton, OrderUpdateBtn});
OrderInfoPanelLayout.setVerticalGroup(
OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderCUSTIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderCustNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderNumberCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderNumberLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaCatNumText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderMediaCatNumLbl))
.addGap(8, 8, 8)
.addComponent(OrderMediaTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeShirtRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypeTrophyRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderTypePlaqueRB)
.addGap(40, 40, 40)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderTotalText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderTotalLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OrderPaymentTypeLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderAccountPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderDeliverPayRB)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderDepositText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderDepositLbl)))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(OrderContentLbl))
.addGroup(OrderInfoPanelLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(OrderContentText, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(OrderSearchButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderCreateBtn)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderUpdateBtn)
.addComponent(OrderStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderStatusLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OrderMediaStatusLbl)
.addComponent(OrderMediaStatusCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OrderClearFieldsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
.addComponent(OrderSearchLbl)
.addGap(18, 18, 18)
.addGroup(OrderInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OrderCreatedByLbl)
.addComponent(OrderAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OrderVerifyByLbl)
.addGap(51, 51, 51))
);
OrderInfoPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {OrderCUSTIDText, OrderDepositText, OrderMediaCatNumText, OrderMediaStatusCB, OrderStatusCB, OrderTotalText});
OrderTabbedPane.addTab("Order Info", OrderInfoPanel);
OVSubmitButton.setText("Submit/Assign");
OVSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSubmitButtonActionPerformed(evt);
}
});
OVClearFieldButton.setText("Clear Fields");
OVClearFieldButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVClearFieldButtonActionPerformed(evt);
}
});
OVSearchButton.setText("Search");
OVSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVSearchButtonActionPerformed(evt);
}
});
OVCorrectNameLbl.setText("Correct Name");
OVAcctNumLbl.setText("Correct Account Number");
OVMediaNumLbl.setText("Valid Media Cat. #");
OVContentLbl.setText("Valid Content");
OVNameBG.add(OVCorrectNamePassRb);
OVCorrectNamePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNamePassRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumPassRb);
OVAcctNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumPassRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumPassRb);
OVMediaNumPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumPassRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentPassRb);
OVContentPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentPassRbActionPerformed(evt);
}
});
OVNameBG.add(OVCorrectNameFailRb);
OVCorrectNameFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVCorrectNameFailRbActionPerformed(evt);
}
});
OVAccountBG.add(OVAcctNumFailRb);
OVAcctNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVAcctNumFailRbActionPerformed(evt);
}
});
OVMediaBG.add(OVMediaNumFailRb);
OVMediaNumFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVMediaNumFailRbActionPerformed(evt);
}
});
OVContentBG.add(OVContentFailRb);
OVContentFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVContentFailRbActionPerformed(evt);
}
});
OVCommentsText.setColumns(20);
OVCommentsText.setRows(5);
OVCommentsTB.setViewportView(OVCommentsText);
OVCommentsLbl.setText("Additional Comments");
OVNameFailText.setEditable(false);
OVAcctNumFailText.setEditable(false);
OVMediaFailText.setEditable(false);
OVContentFailText.setEditable(false);
OVPassLbl.setText("Pass");
OVFailLbl.setText("Fail");
OVReasonLbl.setText("Reason for Failure");
OVDepositBG.add(OVDepositPassRb);
OVDepositPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositPassRbActionPerformed(evt);
}
});
OVDepositLbl.setText("Sufficient Deposit");
OVDepositBG.add(OVDepositFailRb);
OVDepositFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVDepositFailRbActionPerformed(evt);
}
});
OVPaymentBG.add(OVPayTypeFailRb);
OVPayTypeFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypeFailRbActionPerformed(evt);
}
});
OVPayTypePassLbl.setText("Payment Type");
OVDepositFailText.setEditable(false);
OVPayTypeFailText.setEditable(false);
OVPaymentBG.add(OVPayTypePassRb);
OVPayTypePassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OVPayTypePassRbActionPerformed(evt);
}
});
OVNumberLbl.setText("Verification Number");
OVContentValLbl.setToolTipText("");
OVContentValLbl.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
OVContentValLblMouseClick(evt);
}
});
OVAssignEmpCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
OVAssignEmpLbl.setText("Assign Printer/Engraver");
OVOrderNumLbl.setText("Order Number");
OVVerifyByLbl.setText("Order Verified by ******");
OVCreateByLbl.setText("Order Created by ******");
OVAssignedToLbl.setText("Work Assigned to ******");
OVButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
javax.swing.GroupLayout OrderVerifyPanelLayout = new javax.swing.GroupLayout(OrderVerifyPanel);
OrderVerifyPanel.setLayout(OrderVerifyPanelLayout);
OrderVerifyPanelLayout.setHorizontalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVNumberLbl)
.addComponent(OVOrderNumLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVCorrectNameLbl)
.addComponent(OVAcctNumLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVContentLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVDepositLbl))
.addGap(15, 15, 15)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositPassRb)
.addComponent(OVPayTypePassRb)
.addComponent(OVContentPassRb)
.addComponent(OVMediaNumPassRb)
.addComponent(OVAcctNumPassRb)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVPassLbl))
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositFailRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVContentFailRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVFailLbl))
.addComponent(OVMediaNumFailRb, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVNameFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(OVReasonLbl))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVButtonLbl)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVVerifyByLbl)
.addComponent(OVCreateByLbl))
.addGap(48, 48, 48)
.addComponent(OVAssignedToLbl))
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OVAssignEmpLbl))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVDepositValLbl)
.addComponent(OVPayTypeValLbl)
.addComponent(OVContentValLbl)
.addComponent(OVMediaCatValLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVCustNameValLbl)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVSubmitButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVClearFieldButton)))
.addGap(373, 419, Short.MAX_VALUE))))
);
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVAcctNumFailText, OVContentFailText, OVMediaFailText, OVNameFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVDepositFailText, OVPayTypeFailText});
OrderVerifyPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {OVOrderIDText, OVerIDText});
OrderVerifyPanelLayout.setVerticalGroup(
OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVOrderNumLbl)
.addComponent(OVOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVNumberLbl)
.addComponent(OVerIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVPassLbl)
.addComponent(OVFailLbl)
.addComponent(OVReasonLbl)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVCustNameValLbl)
.addComponent(OVCorrectNameLbl)
.addComponent(OVCorrectNamePassRb)
.addComponent(OVCorrectNameFailRb)
.addComponent(OVNameFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVAcctNumLbl)
.addComponent(OVCustIDValLbl)
.addComponent(OVAcctNumPassRb)
.addComponent(OVAcctNumFailRb)
.addComponent(OVAcctNumFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVMediaCatValLbl)
.addComponent(OVMediaNumLbl)
.addComponent(OVMediaNumPassRb)
.addComponent(OVMediaNumFailRb)
.addComponent(OVMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVContentValLbl)
.addComponent(OVContentLbl)
.addComponent(OVContentPassRb)
.addComponent(OVContentFailRb)
.addComponent(OVContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVPayTypeValLbl)
.addComponent(OVPayTypePassLbl)
.addComponent(OVPayTypePassRb)
.addComponent(OVPayTypeFailRb)
.addComponent(OVPayTypeFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(OVDepositValLbl)
.addComponent(OVDepositLbl)
.addComponent(OVDepositPassRb)
.addComponent(OVDepositFailRb)
.addComponent(OVDepositFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVAssignEmpLbl)
.addComponent(OVCommentsLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(OrderVerifyPanelLayout.createSequentialGroup()
.addComponent(OVCommentsTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(OVSearchButton)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVClearFieldButton)
.addComponent(OVSubmitButton))))
.addComponent(OVAssignEmpCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addComponent(OVButtonLbl)
.addGap(1, 1, 1)
.addGroup(OrderVerifyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(OVCreateByLbl)
.addComponent(OVAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(OVVerifyByLbl)
.addContainerGap(176, Short.MAX_VALUE))
);
OrderTabbedPane.addTab("Order Verify", OrderVerifyPanel);
QASubmitButton.setText("Submit");
QASubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASubmitButtonActionPerformed(evt);
}
});
QAClearButton.setText("Clear Fields");
QAClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAClearButtonActionPerformed(evt);
}
});
QASearchButton.setText("Search");
QASearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QASearchButtonActionPerformed(evt);
}
});
QAContentLbl.setText("Correct Order Content");
QAMediaLbl.setText("Correct Order Media");
QAMediaFinishLbl.setText("Media Finish");
QAWorkmanshipLbl.setText("Workmanship");
QAContentBG.add(QAContentCheckPassRb);
QAContentCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckPassRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckPassRb);
QAMediaCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckPassRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckPassRb);
QAMediaFinishCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckPassRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckPassRb);
QAWorkmanshipCheckPassRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckPassRbActionPerformed(evt);
}
});
QAContentBG.add(QAContentCheckFailRb);
QAContentCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAContentCheckFailRbActionPerformed(evt);
}
});
QAMediaBG.add(QAMediaCheckFailRb);
QAMediaCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaCheckFailRbActionPerformed(evt);
}
});
QAMediaFinishBG.add(QAMediaFinishCheckFailRb);
QAMediaFinishCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAMediaFinishCheckFailRbActionPerformed(evt);
}
});
QAWorkmanshipBG.add(QAWorkmanshipCheckFailRb);
QAWorkmanshipCheckFailRb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QAWorkmanshipCheckFailRbActionPerformed(evt);
}
});
QACorrectiveActionText.setColumns(20);
QACorrectiveActionText.setRows(5);
QACorrectiveActionTB.setViewportView(QACorrectiveActionText);
QACommentLbl.setText("Comments");
QAPassLbl.setText("Pass");
QAFailLbl.setText("Fail");
QAFailCommentLbl.setText("Reason for Failure");
QAVerifiedByLbl.setText("Order Verified by ******");
QACreatedByLbl.setText("Order Created by ******");
QAAssignedToLbl.setText("Work Assigned to ******");
QAOrderIDLbl.setText("Order Number");
QAIDLbl.setText("QA Inspection Number");
QAButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
QAButtonLbl.setText("* Use only one field for searches");
javax.swing.GroupLayout QAPanelLayout = new javax.swing.GroupLayout(QAPanel);
QAPanel.setLayout(QAPanelLayout);
QAPanelLayout.setHorizontalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(120, 120, 120)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAOrderIDLbl)
.addComponent(QAIDLbl))
.addGap(23, 23, 23)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAVerifiedByLbl)
.addComponent(QACreatedByLbl))
.addGap(48, 48, 48)
.addComponent(QAAssignedToLbl))
.addGroup(QAPanelLayout.createSequentialGroup()
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAMediaLbl)
.addComponent(QAMediaFinishLbl)
.addComponent(QAWorkmanshipLbl)
.addComponent(QAContentLbl))
.addGap(17, 17, 17)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAPassLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentCheckFailRb)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAFailLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentFailText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAFailCommentLbl)))
.addComponent(QACommentLbl)
.addGroup(QAPanelLayout.createSequentialGroup()
.addComponent(QASearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QASubmitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAClearButton))
.addComponent(QAOrderIDText, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
.addComponent(QAIDText)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)))
.addContainerGap(197, Short.MAX_VALUE))
);
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAContentFailText, QAMediaFailText, QAMediaFinishFailText, QAWorkmanshipFailText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAIDText, QAOrderIDText});
QAPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {QAClearButton, QASearchButton, QASubmitButton});
QAPanelLayout.setVerticalGroup(
QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(QAPanelLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAOrderIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAOrderIDLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAIDLbl))
.addGap(24, 24, 24)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QAPassLbl)
.addComponent(QAFailLbl)
.addComponent(QAFailCommentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAContentFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAContentCheckFailRb)
.addComponent(QAContentCheckPassRb)
.addComponent(QAContentLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaCheckFailRb)
.addComponent(QAMediaCheckPassRb)
.addComponent(QAMediaLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAMediaFinishCheckFailRb)
.addComponent(QAMediaFinishFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAMediaFinishCheckPassRb)
.addComponent(QAMediaFinishLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QAWorkmanshipFailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QAWorkmanshipCheckFailRb)
.addComponent(QAWorkmanshipCheckPassRb)
.addComponent(QAWorkmanshipLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
.addComponent(QACommentLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QACorrectiveActionTB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(QASearchButton)
.addComponent(QASubmitButton)
.addComponent(QAClearButton))
.addGap(2, 2, 2)
.addComponent(QAButtonLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(QAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(QACreatedByLbl)
.addComponent(QAAssignedToLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(QAVerifiedByLbl)
.addGap(88, 88, 88))
);
OrderTabbedPane.addTab("Quality Assurance", QAPanel);
WSCInterface.addTab("Order", OrderTabbedPane);
InvItemIDLbl.setText("Item Number");
InvManufacturerIdLbl.setText("Manufacturer");
InvQtyOnHandLbl.setText("On Hand");
InvQtyOnOrderLbl.setText("On Order");
InvDeliveryDateLbl.setText("Delivery Date");
InvOrderButton.setText("Order/Mark Sold");
InvOrderButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvOrderButtonActionPerformed(evt);
}
});
InvClearButton.setText("Clear Fields");
InvClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvClearButtonActionPerformed(evt);
}
});
InvSearchButton.setText("Search");
InvSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InvSearchButtonActionPerformed(evt);
}
});
InvItemNameLbl.setText("Item Name");
InvButtonLbl.setForeground(new java.awt.Color(255, 51, 51));
InvButtonLbl.setText("* Use only one field for searches");
InvOrderIdLbl.setText("Order");
InvManufacturerItemList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
InvManufacturerItemScrollPane.setViewportView(InvManufacturerItemList);
InvManufacturerItemLbl.setText("Items:");
javax.swing.GroupLayout InventoryPanelLayout = new javax.swing.GroupLayout(InventoryPanel);
InventoryPanel.setLayout(InventoryPanelLayout);
InventoryPanelLayout.setHorizontalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(137, 137, 137)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvDeliveryDateLbl)
.addComponent(InvQtyOnOrderLbl)
.addComponent(InvQtyOnHandLbl)
.addComponent(InvItemNameLbl)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvItemIDLbl)
.addComponent(InvSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvOrderIdLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOrderButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(InvOnOrderText)
.addComponent(InvOnHandText)
.addComponent(InvItemNameText)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvItemIdText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvClearButton))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InvManufacturerItemLbl)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(InvButtonLbl))
.addContainerGap(294, Short.MAX_VALUE))
);
InventoryPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {InvClearButton, InvDeliveryDateText, InvItemIdText, InvItemNameText, InvManufacturerIdText, InvOnHandText, InvOnOrderText, InvOrderButton, InvOrderIdText, InvSearchButton});
InventoryPanelLayout.setVerticalGroup(
InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(93, 93, 93)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvOrderIdLbl)
.addComponent(InvOrderIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvItemIDLbl)
.addComponent(InvItemIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(InvManufacturerIdLbl)
.addComponent(InvManufacturerIdText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvItemNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvItemNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnHandText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnHandLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvOnOrderText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvQtyOnOrderLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvDeliveryDateText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(InvDeliveryDateLbl)))
.addGroup(InventoryPanelLayout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(InvManufacturerItemLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvManufacturerItemScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(InventoryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(InvSearchButton)
.addComponent(InvOrderButton)
.addComponent(InvClearButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InvButtonLbl)
.addContainerGap(307, Short.MAX_VALUE))
);
WSCInterface.addTab("Inventory", InventoryPanel);
EmpFNameLbl.setText("First Name");
EmpLNameLbl.setText("Last Name");
EmpSearchButton.setText("Search");
EmpSearchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSearchButtonActionPerformed(evt);
}
});
EmpSubmitButton.setText("Create/Update");
EmpSubmitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpSubmitButtonActionPerformed(evt);
}
});
emOrdersLst.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
emOrdersLst.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
emOrdersLstValueChanged(evt);
}
});
EmpOrderLB.setViewportView(emOrdersLst);
EmpOrderLbl.setText("Order(s):");
EmpClearButton.setText("Clear Fields");
EmpClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpClearButtonActionPerformed(evt);
}
});
EmpActiveOrderLbl1.setForeground(new java.awt.Color(255, 0, 0));
EmpActiveOrderLbl1.setText("*Active orders in red");
EMPIDLbl.setText("Employee id");
EmpTypeCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TS", "Item 1", "Item 2", "Item 3", "Item 4" }));
EmpTypeCB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EmpTypeCBActionPerformed(evt);
}
});
EmpTypeLbl.setText("Employee Type");
EmpSearchLbl.setForeground(new java.awt.Color(255, 51, 51));
EmpSearchLbl.setText("* Use only one field for searches");
jLabel1.setText("Email Address");
jLabel3.setText("Login Password");
jLabel4.setText("Confirm Password");
javax.swing.GroupLayout EmployeeInfoPanelLayout = new javax.swing.GroupLayout(EmployeeInfoPanel);
EmployeeInfoPanel.setLayout(EmployeeInfoPanelLayout);
EmployeeInfoPanelLayout.setHorizontalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(135, 135, 135)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(EmpTypeLbl)
.addComponent(jLabel1)
.addComponent(EmpLNameLbl)
.addComponent(EmpFNameLbl)
.addComponent(EMPIDLbl))
.addGap(27, 27, 27)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(EmpActiveOrderLbl1))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EmpOrderLbl)
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EmpSearchLbl)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addComponent(EmpSearchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EmpSubmitButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpClearButton)))
.addContainerGap(241, Short.MAX_VALUE))
);
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDCB, EmpClearButton, EmpEmail, EmpFNameText, EmpLNameText, EmpPass, EmpPassConfirm, EmpSubmitButton, EmpTypeCB});
EmployeeInfoPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {EMPIDLbl, EmpFNameLbl, EmpLNameLbl, EmpSearchButton, EmpTypeLbl, jLabel1, jLabel3, jLabel4});
EmployeeInfoPanelLayout.setVerticalGroup(
EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(86, 86, 86)
.addComponent(EmpOrderLbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EMPIDLbl)
.addComponent(EMPIDCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpFNameLbl)
.addComponent(EmpFNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpLNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpLNameLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel1)
.addComponent(EmpEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpTypeCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(EmpTypeLbl))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(EmpPassConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addComponent(EmpOrderLB, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, EmployeeInfoPanelLayout.createSequentialGroup()
.addGroup(EmployeeInfoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(EmpSubmitButton)
.addComponent(EmpClearButton)
.addComponent(EmpSearchButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EmpSearchLbl))
.addGroup(EmployeeInfoPanelLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(EmpActiveOrderLbl1)))
.addContainerGap(217, Short.MAX_VALUE))
);
WSCInterface.addTab("Employee Info", EmployeeInfoPanel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 789, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(WSCInterface, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("");
}// </editor-fold>//GEN-END:initComponents
/* Brad Clawson: These class objects are created to represent the global objects
* that are passed between the tabs in the GUI -
*/
private Employee login = new Employee();
private Customer workingCustomer = new Customer();
private Order workingOrder = new Order();
private OrderVerify workingOV = null;
private QAReport workingQA = new QAReport();
private InventoryItem workingII = new InventoryItem();
public void HideEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Hide password employee fields by default">
EmpPass.setVisible(false);
EmpPassConfirm.setVisible(false);
jLabel3.setVisible(false);
jLabel4.setVisible(false);
// </editor-fold>
}
public void ShowEmpPassword()
{
// <editor-fold defaultstate="collapsed" desc="Show password employee fields by default">
EmpPass.setVisible(true);
EmpPassConfirm.setVisible(true);
jLabel3.setVisible(true);
jLabel4.setVisible(true);
// </editor-fold>
}
private void setOrderNumberCBModel(ArrayList<Order> orders) {
this.OrderNumberCB.removeAllItems();
for (Order o : orders) {
this.OrderNumberCB.addItem(o);
}
}
private void populateOrderTab(Order order) {
// Media Type Radio Buttons
if (order.getMediaType() != null) {
switch (order.getMediaType().toLowerCase()) {
case "trophy":
this.OrderTypeTrophyRB.setSelected(true);
break;
case "plaque":
this.OrderTypePlaqueRB.setSelected(true);
break;
case "shirt":
this.OrderTypeShirtRB.setSelected(true);
break;
default:
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
}
}
// Set OrderTotalText
this.OrderTotalText.setText(String.format("%.2f", order.getTotal()));
// Set OrderDepositText
this.OrderDepositText.setText(String.format("%.2f", order.getDeposit()));
// Set Accout Payment Radio button
if (order.getPaymentOnAccount())
this.OrderAccountPayRB.setSelected(true);
else if (!order.getPaymentOnAccount())
this.OrderDeliverPayRB.setSelected(true);
// Set Order Status CB
this.OrderStatusCB.removeAllItems();
for (Order.OrderStatus os : Order.OrderStatus.values())
this.OrderStatusCB.addItem(os.toString());
this.OrderStatusCB.setSelectedItem(order.getOrderStatus());
// Set the MediaStatusCB
this.OrderMediaStatusCB.removeAllItems();
for (Order.MediaStatus ms : Order.MediaStatus.values())
this.OrderMediaStatusCB.addItem(order.getMediaStatus());
this.OrderMediaStatusCB.setSelectedItem(order.getMediaStatus());
// Set Content Text
this.OrderContentText.setText(order.getContent());
this.OrderContentText.setEditable(true);
}
private void selectOrderByIndex(int index) {
Order order = (Order)this.OrderNumberCB.getItemAt(index);
this.populateOrderTab(order);
}
private void CustStateCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustStateCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_CustStateCBActionPerformed
private void CustClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustClearButtonActionPerformed
//Clear all fields on customer info
CustClear();
}//GEN-LAST:event_CustClearButtonActionPerformed
public void CustClear() {
//Jacob: Created clear method as it will need called once the customer is created.
CUSTIDCB.setText("");
CustFNameText.setText("");
CustLNameText.setText("");
CustOrgText.setText("");
CustStreet1Text.setText("");
CustStreet2Text.setText("");
CustCityText.setText("");
CustZipText.setText("");
CustPhoneText.setText("");
CustEmailText.setText("");
CustStateCB.setSelectedIndex(0);
custOrdLst.setListData(new Object[0]);
}
private void CustCreateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustCreateButtonActionPerformed
//Jacob: Added Try and Catch to check if parse was successful
//if not through a message explaining
boolean CustExist = false;
String temp;
try{
//Get address and assign an empty string if it doesnt exist
if ("".equals(CustStreet1Text.getText()))
{
temp = "";
}
else
{
temp = CustStreet1Text.getText();
}
//Check if customer exists
CustExist = Customer.isCustomer(Integer.parseInt(CUSTIDCB.getText()),temp);
//If the customer doesnt exist create them else cust already exists update
if (CustExist == false)
{
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.createCust(customer);
JOptionPane.showMessageDialog(null, "Customer created successfully.");
// CustClear();
}
else
{
//Update the customer
Customer customer = new Customer(Integer.parseInt(CUSTIDCB.getText()),
CustFNameText.getText(),CustLNameText.getText(), CustOrgText.getText(),
CustStreet1Text.getText(),CustStreet2Text.getText(),CustCityText.getText(),
CustStateCB.getSelectedItem().toString(),Integer.parseInt(CustZipText.getText()),
Long.parseLong(CustPhoneText.getText()),CustEmailText.getText());
Customer.updateBy(customer);
JOptionPane.showMessageDialog(null, "Customer updated.");
// CustClear();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "A numeric value is required for the following:\nCustomer ID\nCustomer Zip\nCustomer Phone Number", "Numeric Value Required", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Customer was not created.");
}
}//GEN-LAST:event_CustCreateButtonActionPerformed
private void CustFindButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CustFindButtonActionPerformed
Customer searchCust = null;
ArrayList<String> cust = new ArrayList<String>();
//Search input to specify column to seach
// <editor-fold defaultstate="collapsed" desc="Get Query for cust search">
if (!"".equals(CUSTIDCB.getText()))
{
searchCust = Customer.searchBy("CUSTID", CUSTIDCB.getText());
}
if (!"".equals(CustFNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustFirstName", CustFNameText.getText());
}
if (!"".equals(CustLNameText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustLastName", CustLNameText.getText());
}
if (!"".equals(CustOrgText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustOrg", CustOrgText.getText());
}
if (!"".equals(CustStreet1Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet1", CustStreet1Text.getText());
}
if (!"".equals(CustStreet2Text.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustStreet2", CustStreet2Text.getText());
}
if (!"".equals(CustPhoneText.getText()) & searchCust == null)
{
searchCust = Customer.searchBy("CustPhone", CustPhoneText.getText());
}
//Check if searchCust is null, if not set the customer information
if (searchCust == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
// <editor-fold defaultstate="collapsed" desc="Set customer data to tab">
CUSTIDCB.setText(String.valueOf(searchCust.getCustId()));
CustFNameText.setText(searchCust.getCustFName());
CustLNameText.setText(searchCust.getCustLName());
CustStreet1Text.setText(searchCust.getCustStreet1());
CustStreet2Text.setText(searchCust.getCustStreet2());
CustCityText.setText(searchCust.getCustCity());
CustZipText.setText(String.valueOf(searchCust.getCustZip()));
CustPhoneText.setText(String.valueOf(searchCust.getCustPhone()));
CustEmailText.setText(searchCust.getCustEmail());
CustStateCB.setSelectedItem(searchCust.getCustState());
CustOrgText.setText(searchCust.getCustOrg());
cust = Customer.getOrders(Long.parseLong(CUSTIDCB.getText()));
custOrdLst.setListData(cust.toArray());
// </editor-fold>
}
// </editor-fold>
}//GEN-LAST:event_CustFindButtonActionPerformed
private void LoginPassTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginPassTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginPassTextActionPerformed
private void LoginEMPIDTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginEMPIDTxtActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoginEMPIDTxtActionPerformed
private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginButtonActionPerformed
Login.processLogin(LoginEMPIDTxt.getText(), LoginPassText.getText());
// SetAccessLevel();
}//GEN-LAST:event_LoginButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA Search,Submit,Clear Buttons">
private void QASubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* QAReport object to QAReport.insertOrUpdateQA() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the QAIDText field
* to populate the screen with the information that is searched for and
* verified by the popQA() method. If popQA() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean contentCheck = false, mediaCheck = false, mediaFinishCheck = false,
workmanshipCheck = false, depositCheck = false;
String contentComment = "", mediaComment = "", mediaFinishComment = "",
workmanshipComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if QA check fails
if(QAContentCheckPassRb.isSelected()){
contentCheck = Boolean.TRUE;
}
else if(QAContentCheckFailRb.isSelected()){
contentCheck = Boolean.FALSE;
contentComment = QAContentFailText.getText();
}
if(QAMediaCheckPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(QAMediaCheckFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = QAMediaFailText.getText();
}
if(QAMediaFinishCheckPassRb.isSelected()){
mediaFinishCheck = Boolean.TRUE;
}
else if(QAMediaFinishCheckFailRb.isSelected()){
mediaFinishCheck = Boolean.FALSE;
mediaFinishComment = QAMediaFailText.getText();
}
if(QAWorkmanshipCheckPassRb.isSelected()){
workmanshipCheck = (Boolean.TRUE);
}
else if(QAWorkmanshipCheckFailRb.isSelected()){
workmanshipCheck = (Boolean.FALSE);
workmanshipComment = (QAWorkmanshipFailText.getText());
}
if(QAContentCheckFailRb.isSelected()||
QAMediaCheckFailRb.isSelected()||
QAMediaFinishCheckFailRb.isSelected()||
QAWorkmanshipCheckFailRb.isSelected()){
correctiveActionComment = (QACorrectiveActionText.getText());
}
//Create new QAReport object with screen data to be passed to insertOrUpdateQA()
QAReport newQA = new QAReport((Integer.parseInt(QAIDText.getText())),
Order.getOrder(Integer.parseInt(QAOrderIDText.getText())),
Login.emp, contentCheck, mediaCheck, mediaFinishCheck,
workmanshipCheck, contentComment, mediaComment, mediaFinishComment,
workmanshipComment, correctiveActionComment);
//Object that is returned verifies that the object was created
newQA = QAReport.insertOrUpdateQA(newQA);
//prepare the screen for popQA;
QAIDText.setText(String.valueOf(newQA.getQAID()));
QAOrderIDText.setText("");
//Object is verified a second time through popQA and QAbuttonLbl informs results
if(popQA()){
QAButtonLbl.setText("Create/Update Successful");}
else {
QAButtonLbl.setText("Create/Update Unsuccessful");
}
}//GEN-LAST:event_QASubmitButtonActionPerformed
private void QAClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAClearButtonActionPerformed
//Brad Clawson: Clear information entered into QA tab
QAIDText.setText("");
QAOrderIDText.setText("");
QAContentFailText.setText("");
QAMediaFailText.setText("");
QAMediaFinishFailText.setText("");
QAWorkmanshipFailText.setText("");
QACorrectiveActionText.setText("");
QAContentBG.clearSelection();
QAMediaBG.clearSelection();
QAMediaFinishBG.clearSelection();
QAWorkmanshipBG.clearSelection();
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}//GEN-LAST:event_QAClearButtonActionPerformed
private void QASearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QASearchButtonActionPerformed
//Brad Clawson: This method calls the popQA() method to populate the tab
if(popQA()){
QAButtonLbl.setText("Record Found");
}
else{
QAButtonLbl.setText(QAButtonLbl.getText() + ".\n"+"Record Not Found");
}
}//GEN-LAST:event_QASearchButtonActionPerformed
private Boolean popQA(){
/*
* Brad Clawson: Populates Quality Assurance tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND QAID is null or empty search by OrderID
if ((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("ORDERID", Integer.parseInt(QAOrderIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF QAID is not null or empty AND OrderID is null or empty search by QAID
else if ((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
workingQA = QAReport.getQAby("QAID", Integer.parseInt(QAIDText.getText()));
QAIDText.setBackground(Color.white);
QAOrderIDText.setBackground(Color.white);
}
//IF OrderID and QAID are null or empty, notify user to enter proper search criteria
else if((QAOrderIDText.getText() == null || QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() == null || QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Please enter a search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//IF OrderID and QAID both not null or empty, notify user to enter single search criteria
else if((QAOrderIDText.getText() != null && !QAOrderIDText.getText().isEmpty())
&& (QAIDText.getText() != null && !QAIDText.getText().isEmpty())){
QAButtonLbl.setText("Use a single search Criteria");
QAButtonLbl.setVisible(true);
QAIDText.setBackground(Color.YELLOW);
QAOrderIDText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//fill tab content with values from QAReport that was returned in search
QAOrderIDText.setText(String.valueOf(workingQA.getOrder().getORDID()));
QAIDText.setText(String.valueOf(workingQA.getQAID()));
//select correct radio boxes and set fail comments editable or ineditable
if(workingQA.getContentCheck()){
QAContentCheckPassRb.setSelected(true);
QAContentFailText.setEditable(false);}
else if(!workingQA.getContentCheck()){
QAContentCheckFailRb.setSelected(true);
QAContentFailText.setText(workingQA.getContentFailComment());
QAContentFailText.setEditable(true);}
if(workingQA.getMediaCheck()){
QAMediaCheckPassRb.setSelected(true);
QAMediaFailText.setEditable(false);}
else if(!workingQA.getMediaCheck()){
QAMediaCheckFailRb.setSelected(true);
QAMediaFailText.setText(workingQA.getMediaFailComment());
QAMediaFailText.setEditable(true);}
if(workingQA.getMediaFinishCheck()){
QAMediaFinishCheckPassRb.setSelected(true);
QAMediaFinishFailText.setEditable(false);}
else if(!workingQA.getMediaFinishCheck()){
QAMediaFinishCheckFailRb.setSelected(true);
QAMediaFinishFailText.setText(workingQA.getMediaFinishFailComment());
QAMediaFinishFailText.setEditable(true);}
if(workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckPassRb.setSelected(true);
QAWorkmanshipFailText.setEditable(false);}
else if(!workingQA.getWorkmanshipCheck()){
QAWorkmanshipCheckFailRb.setSelected(true);
QAWorkmanshipFailText.setText(workingQA.getWorkmanshipFailComment());
QAWorkmanshipFailText.setEditable(true);}
//page successfully populated return true to indicate success
return true;
}
private void QAOrderIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad:reset background color if changed from invalid search param
QAOrderIDText.setBackground(Color.white);
}
private void QAIDTextFocusGained(java.awt.event.FocusEvent evt) {
//Brad: reset background color if changed from invalid search param
QAIDText.setBackground(Color.white);
}
//</editor-fold>
private void OrderClearFieldsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderClearFieldsButtonActionPerformed
this.OrderCUSTIDText.setText("");
this.OrderNumberCB.removeAllItems();
this.OrderMediaCatNumText.setText("");
this.OrderTypePlaqueRB.setSelected(false);
this.OrderTypeShirtRB.setSelected(false);
this.OrderTypeTrophyRB.setSelected(false);
this.OrderTotalText.setText("");
this.OrderAccountPayRB.setSelected(false);
this.OrderDeliverPayRB.setSelected(false);
this.OrderDepositText.setText("");
this.OrderStatusCB.setSelectedIndex(0);
this.OrderMediaStatusCB.setSelectedIndex(0);
this.OrderContentText.setText("");
}//GEN-LAST:event_OrderClearFieldsButtonActionPerformed
private void OrderCreateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderCreateBtnActionPerformed
Customer cust = Customer.searchBy("CUSTID", "1");
String content = this.OrderContentText.getText();
boolean onAcct = false;
String mediaType = "";
if (this.OrderTypePlaqueRB.isSelected())
mediaType = "plaque";
else if (this.OrderTypeShirtRB.isSelected())
mediaType = "shirt";
else if (this.OrderTypeTrophyRB.isSelected())
mediaType = "trophy";
if (this.OrderAccountPayRB.isSelected())
onAcct = true;
float total = Float.parseFloat(this.OrderTotalText.getText());
float deposit = Float.parseFloat(this.OrderDepositText.getText());
String orderStatus = (String)this.OrderStatusCB.getSelectedItem();
String mediaStatus = (String)this.OrderMediaStatusCB.getSelectedItem();
Employee employee;
if (Login.emp != null)
employee = Login.emp;
else
employee = Employee.searchBy(1);
// Create new Order obj
Order order = new Order(cust, 0, mediaType, content, onAcct, total, deposit, orderStatus, mediaStatus, employee);
order = Order.createOrder(order); // Put into DB
this.populateOrderTab(order); // Populate view from the created obj (see errors this way)
}//GEN-LAST:event_OrderCreateBtnActionPerformed
private void OrderSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderSearchButtonActionPerformed
if (this.OrderCUSTIDText.getText().length() > 0) {
this.orders = Order.getOrders(Integer.parseInt(this.OrderCUSTIDText.getText()));
this.setOrderNumberCBModel(orders);
this.selectOrderByIndex(0);
}
else {
JOptionPane.showMessageDialog(null, "Please search by Customer ID", "Error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_OrderSearchButtonActionPerformed
private void LogoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutButtonActionPerformed
Login.processLogout();
/* //Brad: make all tabs except login invisible Login action will set user access
CustomerInfoPanel.setVisible(false);
EmployeeInfoPanel.setVisible(false);
OrderTabbedPane.setVisible(false);
OrderInfoPanel.setVisible(false);
OrderVerifyPanel.setVisible(false);
QAPanel.setVisible(false);
InventoryPanel.setVisible(false);
*/
}//GEN-LAST:event_LogoutButtonActionPerformed
private void EmpSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSearchButtonActionPerformed
// TODO add your handling code here:
Employee emp = null;
ArrayList<String> orders = new ArrayList<String>();
if (!"".equals(EMPIDCB.getText()))
{
emp = Employee.searchBy(Long.parseLong(EMPIDCB.getText()));
orders = Employee.getOrders(Long.parseLong(EMPIDCB.getText()));
emOrdersLst.setListData(orders.toArray());
}
if (emp == null)
{
JOptionPane.showMessageDialog(null, "A search value is required", "Search Value", JOptionPane.INFORMATION_MESSAGE);
}
else
{
EMPIDCB.setText(String.valueOf(emp.getEmpId()));
EmpFNameText.setText(emp.getFirstName());
EmpLNameText.setText(emp.getLastName());
EmpEmail.setText(emp.getEmail());
EmpTypeCB.setSelectedItem(emp.getEmpType());
ShowEmpPassword();
}
}//GEN-LAST:event_EmpSearchButtonActionPerformed
private void EmpSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpSubmitButtonActionPerformed
boolean empExist = false;
boolean empUser = false;
String temp;
try{
//Check if employee exists
empExist = Employee.isEmployee(Long.parseLong(EMPIDCB.getText()));
//If the employee doesn't exist create them else employee already exists update
if (empExist == false)
{
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.createEmp(emp);
JOptionPane.showMessageDialog(null, "Employee created successfully.");
//EmpClear();
HideEmpPassword();
}
else
{
String passText = new String(EmpPass.getPassword());
String passTextConfirm = new String(EmpPassConfirm.getPassword());
if (!passText.equals(passTextConfirm))
{
JOptionPane.showMessageDialog(null, "Employee password does not match.");
}
else
{
//Update the employee
Employee emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateBy(emp);
emp = null;
empUser = Employee.empUserExist(Long.parseLong(EMPIDCB.getText()));
if (empUser == false)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.addUserLogin(emp);
}
if (empUser == true)
{
emp = new Employee(EmpFNameText.getText(),EmpLNameText.getText(),Long.parseLong(EMPIDCB.getText()),EmpEmail.getText(),EmpTypeCB.getSelectedItem().toString());
Employee.updateUserLogin(emp);
}
JOptionPane.showMessageDialog(null, "Employee updated.");
//EmpClear();
HideEmpPassword();
}
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Employee was not created.");
}
}//GEN-LAST:event_EmpSubmitButtonActionPerformed
public void EmpClear(){
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpTypeCB.setSelectedIndex(0);
}
private void EmpClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpClearButtonActionPerformed
// Clear Employee data
EMPIDCB.setText("");
EmpFNameText.setText("");
EmpLNameText.setText("");
EmpEmail.setText("");
EmpPass.setText("");
EmpPassConfirm.setText("");
EmpTypeCB.setSelectedIndex(0);
emOrdersLst.setListData(new Object[0]);
}//GEN-LAST:event_EmpClearButtonActionPerformed
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: QA radio buttons">
private void QAContentCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAContentFailText.setEditable(false);
}//GEN-LAST:event_QAContentCheckPassRbActionPerformed
private void QAMediaCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFailText.setEditable(false);
}//GEN-LAST:event_QAMediaCheckPassRbActionPerformed
private void QAMediaFinishCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAMediaFinishFailText.setEditable(false);
}//GEN-LAST:event_QAMediaFinishCheckPassRbActionPerformed
private void QAWorkmanshipCheckPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
QAWorkmanshipFailText.setEditable(false);
}//GEN-LAST:event_QAWorkmanshipCheckPassRbActionPerformed
private void QAContentCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAContentCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAContentFailText.setEditable(true);
}//GEN-LAST:event_QAContentCheckFailRbActionPerformed
private void QAMediaCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFailText.setEditable(true);
}//GEN-LAST:event_QAMediaCheckFailRbActionPerformed
private void QAMediaFinishCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAMediaFinishCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAMediaFinishFailText.setEditable(true);
}//GEN-LAST:event_QAMediaFinishCheckFailRbActionPerformed
private void QAWorkmanshipCheckFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QAWorkmanshipCheckFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
QAWorkmanshipFailText.setEditable(true);
}//GEN-LAST:event_QAWorkmanshipCheckFailRbActionPerformed
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: OV radio buttons">
private void OVPayTypePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVPayTypePassRb.isSelected()){
OVPayTypeFailText.setEditable(false);
}
}//GEN-LAST:event_OVPayTypePassRbActionPerformed
private void OVPayTypeFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVPayTypeFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVPayTypeFailRb.isSelected()){
OVPayTypeFailText.setEditable(true);
}
}//GEN-LAST:event_OVPayTypeFailRbActionPerformed
private void OVDepositFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVDepositFailRb.isSelected()){
OVDepositFailText.setEditable(true);
}
}//GEN-LAST:event_OVDepositFailRbActionPerformed
private void OVDepositPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVDepositPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVDepositPassRb.isSelected()){
OVDepositFailText.setEditable(false);
}
}//GEN-LAST:event_OVDepositPassRbActionPerformed
private void OVContentFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVContentFailRb.isSelected()){
OVContentFailText.setEditable(true);
}
}//GEN-LAST:event_OVContentFailRbActionPerformed
private void OVMediaNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVMediaNumFailRb.isSelected()){
OVMediaFailText.setEditable(true);
}
}//GEN-LAST:event_OVMediaNumFailRbActionPerformed
private void OVAcctNumFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVAcctNumFailRb.isSelected()){
OVAcctNumFailText.setEditable(true);
}
}//GEN-LAST:event_OVAcctNumFailRbActionPerformed
private void OVCorrectNameFailRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNameFailRbActionPerformed
//Brad: when failRb is pressed, failure comment becomes editable
if(OVCorrectNameFailRb.isSelected()){
OVNameFailText.setEditable(true);
}
}//GEN-LAST:event_OVCorrectNameFailRbActionPerformed
private void OVContentPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVContentPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVContentPassRb.isSelected()){
OVContentFailText.setEditable(false);
}
}//GEN-LAST:event_OVContentPassRbActionPerformed
private void OVMediaNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVMediaNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVMediaNumPassRb.isSelected()){
OVMediaFailText.setEditable(false);
}
}//GEN-LAST:event_OVMediaNumPassRbActionPerformed
private void OVAcctNumPassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVAcctNumPassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVAcctNumPassRb.isSelected()){
OVAcctNumFailText.setEditable(false);
}
}//GEN-LAST:event_OVAcctNumPassRbActionPerformed
private void OVCorrectNamePassRbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVCorrectNamePassRbActionPerformed
//Brad: when passRb is pressed, failure comment becomes uneditable
if(OVCorrectNamePassRb.isSelected()){
OVNameFailText.setEditable(false);
}
}//GEN-LAST:event_OVCorrectNamePassRbActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Brad Clawson: OV Search,Submit,Clear Buttons">
private void OVSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSearchButtonActionPerformed
//Brad Clawson: search by OVID or OrderID through popID() and indicate success or failure
if(popOV()){
OVButtonLbl.setText("Record Found");
}
else{
OVButtonLbl.setText(OVButtonLbl.getText()+ ". Record not Found");
}
}//GEN-LAST:event_OVSearchButtonActionPerformed
private Boolean popOV(){
/*
* Brad Clawson: Populates Order Verify tab by searching either Order Number
* or Verification Number, but not both. If search results
*/
//IF OrderID is not null or empty AND OVID is null or empty search by OrderID
if ((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("ORDERID", Integer.parseInt(OVOrderIDText.getText()));
}
//IF OVID is not null or empty AND OrderID is null or empty search by OVID
else if ((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
workingOV = OrderVerify.getOVby("VERID", Integer.parseInt(OVerIDText.getText()));
}
//If both OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() == null || OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() == null || OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Please enter a Order ID or Verification ID for Search");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
//If neither OVID and OrderID are null or empty notify and return search failed
else if((OVOrderIDText.getText() != null && !OVOrderIDText.getText().isEmpty())
&& (OVerIDText.getText() != null && !OVerIDText.getText().isEmpty())){
OVButtonLbl.setText("Use Only One Field for Searches");
OVButtonLbl.setVisible(true);
//search failed return false
return false;
}
// make Order information available for easy evaluation
OVCustNameValLbl.setVisible(true);
OVCustIDValLbl.setVisible(true);
OVMediaCatValLbl.setVisible(true);
OVContentValLbl.setVisible(true);
OVPayTypeValLbl.setVisible(true);
OVDepositValLbl.setVisible(true);
OVOrderIDText.setText(String.valueOf(workingOV.getOrder().getORDID()));
OVerIDText.setText(String.valueOf(workingOV.getVerID()));
OVCustNameValLbl.setText(workingOV.getOrder().getCustomer().getCustFName()
+ " " + workingOV.getOrder().getCustomer().getCustLName());
OVCustIDValLbl.setText(String.valueOf(workingOV.getOrder().getCustomer().getCustId()));
// OVMedCatValLbl.setText(String.valueOf(workingOV.getOrder().getMedia().getItemID));
OVContentValLbl.setText("(Content)");
OVContentValLbl.setForeground(Color.BLUE);
//set screen values for returned OrderVerify object
if (workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Account");
}
if (!workingOV.getOrder().getPaymentOnAccount()){
OVPayTypeValLbl.setText("On Delivery");
}
OVDepositValLbl.setText(String.valueOf(workingOV.getOrder().getDeposit()));
// OVAssignEmpCB
//set radio button values and set fail comments editable or ineditable
if(workingOV.getNameCheck()){
OVCorrectNamePassRb.setSelected(true);
OVNameFailText.setEditable(false);}
else if(!workingOV.getNameCheck()){
OVCorrectNameFailRb.setSelected(true);
OVNameFailText.setText(workingOV.getNameFailComment());
OVNameFailText.setEditable(true);}
if(workingOV.getAccountCheck()){
OVAcctNumPassRb.setSelected(true);
OVAcctNumFailText.setEditable(false);}
else if(!workingOV.getAccountCheck()){
OVAcctNumFailRb.setSelected(true);
OVAcctNumFailText.setText(workingOV.getAccountFailComment());
OVAcctNumFailText.setEditable(true);}
if(workingOV.getMediaCheck()){
OVMediaNumPassRb.setSelected(true);
OVMediaFailText.setEditable(false);}
else if(!workingOV.getMediaCheck()){
OVMediaNumFailRb.setSelected(true);
OVMediaFailText.setText(workingOV.getMediaFailComment());
OVMediaFailText.setEditable(true);}
if(workingOV.getContentCheck()){
OVContentPassRb.setSelected(true);
OVContentFailText.setEditable(false);}
else if(!workingOV.getContentCheck()){
OVContentFailRb.setSelected(true);
OVContentFailText.setText(workingOV.getContentFailComment());
OVContentFailText.setEditable(true);}
if(workingOV.getPaymentCheck()){
OVPayTypePassRb.setSelected(true);
OVPayTypeFailText.setEditable(false);}
else if(!workingOV.getPaymentCheck()){
OVPayTypeFailRb.setSelected(true);
OVPayTypeFailText.setText(workingOV.getPaymentFailComment());
OVPayTypeFailText.setEditable(true);}
if(workingOV.getDepositCheck()){
OVDepositPassRb.setSelected(true);
OVDepositFailText.setEditable(false);}
else if(!workingOV.getDepositCheck()){
OVDepositFailRb.setSelected(true);
OVDepositFailText.setText(workingOV.getDepositFailComment());
OVDepositFailText.setEditable(true);}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected())
{
OVCommentsText.setText(workingOV.getCorrectiveActionComment());
OVCommentsText.setEditable(true);
}
//tab items successfully populated, return true for success
return true;
}
private void OVClearFieldButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVClearFieldButtonActionPerformed
//Brad Clawson: reset all values on OV tab
OVCustNameValLbl.setText("");
OVCustIDValLbl.setText("");
OVMediaCatValLbl.setText("");
OVContentValLbl.setText("");
OVPayTypeValLbl.setText("");
OVDepositValLbl.setText("");
// OVAssignEmpCB.setText("");
OVOrderIDText.setText("");
OVerIDText.setText("");
OVNameBG.clearSelection();
OVAccountBG.clearSelection();
OVPaymentBG.clearSelection();
OVDepositBG.clearSelection();
OVContentBG.clearSelection();
OVMediaBG.clearSelection();
OVNameFailText.setText("");
OVAcctNumFailText.setText("");
OVMediaFailText.setText("");
OVContentFailText.setText("");
OVPayTypeFailText.setText("");
OVDepositFailText.setText("");
OVCommentsText.setText("");
OVCustNameValLbl.setVisible(false);
OVCustIDValLbl.setVisible(false);
OVMediaCatValLbl.setVisible(false);
OVContentValLbl.setVisible(false);
OVPayTypeValLbl.setVisible(false);
OVDepositValLbl.setVisible(false);
}//GEN-LAST:event_OVClearFieldButtonActionPerformed
private void OVSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OVSubmitButtonActionPerformed
/* Brad Clawson: This method will pass GUI field data in the form of a
* OrderVerify object to OrderVerify.insertOrUpdateOV() that will determine if
* the report id number exists. If the report id does not exist, or is 0,
* the method will create a new record. If the report id does exist the
* method updates that record with the information on the screen. The
* method clears the OrderIDText field and populates the OVIDText field
* to populate the screen with the information that is searched for and
* verified by the popOV() method. If popOV() finds the new or updated
* record, and populates the screen, the button information label will
* indicate that the insert/update was successful. If not successful the
* label will indicate that as well. -
*/
//Assign bool and string variables for object constructor
Boolean nameCheck = false, accountCheck = false, mediaCheck = false,
contentCheck = false,paymentCheck = false, depositCheck = false;
String nameComment = "", accountComment = "", mediaComment = "",
contentComment = "", paymentComment = "", depositComment = "",
correctiveActionComment = "";
//Assign bool values according to the Radio buttons selected
//Set fail comment string values if OV check fails
if(OVCorrectNamePassRb.isSelected()){
nameCheck = Boolean.TRUE;
}
else if(OVCorrectNameFailRb.isSelected()){
nameCheck = Boolean.FALSE;
nameComment = OVNameFailText.getText();
}
if(OVAcctNumPassRb.isSelected()){
accountCheck = Boolean.TRUE;
}
else if(OVAcctNumFailRb.isSelected()){
accountCheck = Boolean.FALSE;
accountComment = OVAcctNumFailText.getText();
}
if(OVMediaNumPassRb.isSelected()){
mediaCheck = Boolean.TRUE;
}
else if(OVMediaNumFailRb.isSelected()){
mediaCheck = Boolean.FALSE;
mediaComment = OVMediaFailText.getText();
}
if(OVContentPassRb.isSelected()){
contentCheck = (Boolean.TRUE);
}
else if(OVContentFailRb.isSelected()){
contentCheck = (Boolean.FALSE);
contentComment = (OVContentFailText.getText());
}
if(OVPayTypePassRb.isSelected()){
paymentCheck = (Boolean.TRUE);
}
else if(OVPayTypeFailRb.isSelected()){
paymentCheck = (Boolean.FALSE);
paymentComment = (OVPayTypeFailText.getText());
}
if (OVDepositPassRb.isSelected()){
depositCheck = (Boolean.TRUE);
}
else if(OVDepositFailRb.isSelected()){
depositCheck = (Boolean.FALSE);
depositComment = (OVDepositFailText.getText());
}
if(OVCorrectNameFailRb.isSelected()||OVAcctNumFailRb.isSelected()||
OVMediaNumFailRb.isSelected()||OVContentFailRb.isSelected()||
OVPayTypeFailRb.isSelected()||OVDepositFailRb.isSelected()){
correctiveActionComment = (OVCommentsText.getText());
}
//Create new OV object with screen data to be passed to insertOrUpdateOV()
OrderVerify newOV = new OrderVerify((Integer.parseInt(OVerIDText.getText())),Login.emp,
Order.getOrder(Integer.parseInt(OVOrderIDText.getText())),
nameCheck, accountCheck, mediaCheck, contentCheck, paymentCheck,
depositCheck, nameComment, accountComment, mediaComment, contentComment,
paymentComment, depositComment,correctiveActionComment);
//Object that is returned verifies that the object was created
newOV = OrderVerify.insertOrUpdateOV(newOV);
//prepare screen for popOV()
OVerIDText.setText(String.valueOf(newOV.getVerID()));
OVOrderIDText.setText("");
//Record is searched for and verified a second time through popOV()
if(popOV()){
OVButtonLbl.setText("Create/Update Successful");}
}//GEN-LAST:event_OVSubmitButtonActionPerformed
//</editor-fold>
private void OrderStatusCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderStatusCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_OrderStatusCBActionPerformed
private void emOrdersLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_emOrdersLstValueChanged
// TODO add your handling code here:
}//GEN-LAST:event_emOrdersLstValueChanged
private void custOrdLstValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_custOrdLstValueChanged
//Add code for customer orders
}//GEN-LAST:event_custOrdLstValueChanged
private void EmpTypeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpTypeCBActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_EmpTypeCBActionPerformed
private void OrderNumberCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OrderNumberCBActionPerformed
if (this.OrderNumberCB.getSelectedIndex() != -1)
this.selectOrderByIndex(this.OrderNumberCB.getSelectedIndex());
}//GEN-LAST:event_OrderNumberCBActionPerformed
private void OrderUpdateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void OVContentValLblMouseClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_OVContentValLblMouseClick
//Brad: popup content in JOption pane for easy access when verifying order
JOptionPane.showMessageDialog(null, workingOV.getOrder().getContent());
}//GEN-LAST:event_OVContentValLblMouseClick
// <editor-fold defaultstate="collapsed" desc="Brad Clawson: InventoryItem Search,Submit,Clear Buttons">
private void InvClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvClearButtonActionPerformed
// Clear Inventory data
InvItemIdText.setText("");
InvManufacturerIdText.setText("");
InvItemNameText.setText("");
InvOnHandText.setText("");
InvOnOrderText.setText("");
InvDeliveryDateText.setText("");
}//GEN-LAST:event_InvClearButtonActionPerformed
private void InvOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvOrderButtonActionPerformed
}//GEN-LAST:event_InvOrderButtonActionPerformed
private void InvSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InvSearchButtonActionPerformed
if(popII()){
InvButtonLbl.setText("Item(s) found");
}
}//GEN-LAST:event_InvSearchButtonActionPerformed
private Boolean popII(){ /*
* Brad Clawson: Populates Inventory Item tab by searching either ItemID Number,
* Manufacturer, or name but not by more than one field.
*/
//search by ITEMID if ManID and ItemName are null or empty
if ((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("ITEMID", InvItemIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by MANID if ITEMID and ItemName are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("MANID", InvManufacturerIdText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//search by ItemName if ManID and ITEMID are null or empty
else if ((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
workingII = InventoryItem.getIIby("Name", InvItemNameText.getText());
InvManufacturerIdText.setBackground(Color.white);
InvItemIdText.setBackground(Color.white);
}
//if search criteria are all null or empty, return false with notification
else if((InvItemIdText.getText() == null || InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() == null || InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() == null || InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Please enter a search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
InvItemNameText.setBackground(Color.YELLOW);
//page not populated, return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())
|| (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
&& (InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//if two search criteria are entere, return false with notification
else if((InvItemNameText.getText() != null && !InvItemNameText.getText().isEmpty())
&& (InvManufacturerIdText.getText() != null && !InvManufacturerIdText.getText().isEmpty())
|| (InvItemIdText.getText() != null && !InvItemIdText.getText().isEmpty())){
InvButtonLbl.setText("Use a single search Criteria");
InvButtonLbl.setVisible(true);
InvManufacturerIdText.setBackground(Color.YELLOW);
InvItemIdText.setBackground(Color.YELLOW);
//page not populated return false for failure
return false;
}
//populate Inventory Item Tab fields
InvItemIdText.setText(String.valueOf(workingII.getItemNumber()));
InvManufacturerIdText.setText(String.valueOf(workingII.getManufacturerID()));
InvItemNameText.setText(workingII.getName());
InvOnHandText.setText(String.valueOf(workingII.getQtyOnHand()));
InvOnOrderText.setText(String.valueOf(workingII.getQtyOnOrder()));
InvDeliveryDateText.setText(workingII.getDeliveryDate());
return true;
}
//</editor-fold>
// <editor-fold defaultstate="collapsed" desc="GUI Variable Declarations">
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField CUSTIDCB;
private javax.swing.JLabel CUSTIDLbl;
private javax.swing.JLabel CustActiveOrderLbl;
private javax.swing.JLabel CustCityLbl;
private javax.swing.JTextField CustCityText;
private javax.swing.JButton CustClearButton;
private javax.swing.JButton CustCreateButton;
private javax.swing.JLabel CustEmailLbl;
private javax.swing.JTextField CustEmailText;
private javax.swing.JLabel CustFNameLbl;
private javax.swing.JTextField CustFNameText;
private javax.swing.JButton CustFindButton;
private javax.swing.JLabel CustLNameLbl;
private javax.swing.JTextField CustLNameText;
private javax.swing.JScrollPane CustOrderListBox;
private javax.swing.JLabel CustOrderListBoxLbl;
private javax.swing.JLabel CustOrgLbl;
private javax.swing.JTextField CustOrgText;
private javax.swing.JLabel CustPhoneLbl;
private javax.swing.JTextField CustPhoneText;
private javax.swing.JComboBox CustStateCB;
private javax.swing.JLabel CustStateLbl;
private javax.swing.JLabel CustStreet1Lbl;
private javax.swing.JTextField CustStreet1Text;
private javax.swing.JLabel CustStreet2Lbl;
private javax.swing.JTextField CustStreet2Text;
private javax.swing.JLabel CustZipLbl;
private javax.swing.JTextField CustZipText;
private javax.swing.JPanel CustomerInfoPanel;
private javax.swing.JTextField EMPIDCB;
private javax.swing.JLabel EMPIDLbl;
private javax.swing.JLabel EmpActiveOrderLbl1;
private javax.swing.JButton EmpClearButton;
private javax.swing.JTextField EmpEmail;
private javax.swing.JLabel EmpFNameLbl;
private javax.swing.JTextField EmpFNameText;
private javax.swing.JLabel EmpLNameLbl;
private javax.swing.JTextField EmpLNameText;
private javax.swing.JScrollPane EmpOrderLB;
private javax.swing.JLabel EmpOrderLbl;
private javax.swing.JPasswordField EmpPass;
private javax.swing.JPasswordField EmpPassConfirm;
private javax.swing.JButton EmpSearchButton;
private javax.swing.JLabel EmpSearchLbl;
private javax.swing.JButton EmpSubmitButton;
private javax.swing.JComboBox EmpTypeCB;
private javax.swing.JLabel EmpTypeLbl;
private javax.swing.JPanel EmployeeInfoPanel;
private javax.swing.JLabel InvButtonLbl;
private javax.swing.JButton InvClearButton;
private javax.swing.JLabel InvDeliveryDateLbl;
private javax.swing.JTextField InvDeliveryDateText;
private javax.swing.JLabel InvItemIDLbl;
private javax.swing.JTextField InvItemIdText;
private javax.swing.JLabel InvItemNameLbl;
private javax.swing.JTextField InvItemNameText;
private javax.swing.JLabel InvManufacturerIdLbl;
private javax.swing.JTextField InvManufacturerIdText;
private javax.swing.JLabel InvManufacturerItemLbl;
private javax.swing.JList InvManufacturerItemList;
private javax.swing.JScrollPane InvManufacturerItemScrollPane;
private javax.swing.JTextField InvOnHandText;
private javax.swing.JTextField InvOnOrderText;
private javax.swing.JButton InvOrderButton;
private javax.swing.JLabel InvOrderIdLbl;
private javax.swing.JTextField InvOrderIdText;
private javax.swing.JLabel InvQtyOnHandLbl;
private javax.swing.JLabel InvQtyOnOrderLbl;
private javax.swing.JButton InvSearchButton;
private javax.swing.JLabel InvSearchLbl5;
private javax.swing.JPanel InventoryPanel;
private javax.swing.JButton LoginButton;
private javax.swing.JLabel LoginEMPIDLbl;
private javax.swing.JTextField LoginEMPIDTxt;
private javax.swing.JPanel LoginPanel;
private javax.swing.JLabel LoginPassLbl;
private javax.swing.JPasswordField LoginPassText;
private javax.swing.JButton LogoutButton;
private javax.swing.ButtonGroup OVAccountBG;
private javax.swing.JRadioButton OVAcctNumFailRb;
private javax.swing.JTextField OVAcctNumFailText;
private javax.swing.JLabel OVAcctNumLbl;
private javax.swing.JRadioButton OVAcctNumPassRb;
private javax.swing.JComboBox OVAssignEmpCB;
private javax.swing.JLabel OVAssignEmpLbl;
private javax.swing.JLabel OVAssignedToLbl;
private javax.swing.JLabel OVButtonLbl;
private javax.swing.JButton OVClearFieldButton;
private javax.swing.JLabel OVCommentsLbl;
private javax.swing.JScrollPane OVCommentsTB;
private javax.swing.JTextArea OVCommentsText;
private javax.swing.ButtonGroup OVContentBG;
private javax.swing.JRadioButton OVContentFailRb;
private javax.swing.JTextField OVContentFailText;
private javax.swing.JLabel OVContentLbl;
private javax.swing.JRadioButton OVContentPassRb;
private javax.swing.JLabel OVContentValLbl;
private javax.swing.JRadioButton OVCorrectNameFailRb;
private javax.swing.JLabel OVCorrectNameLbl;
private javax.swing.JRadioButton OVCorrectNamePassRb;
private javax.swing.JLabel OVCreateByLbl;
private javax.swing.JLabel OVCustIDValLbl;
private javax.swing.JLabel OVCustNameValLbl;
private javax.swing.ButtonGroup OVDepositBG;
private javax.swing.JRadioButton OVDepositFailRb;
private javax.swing.JTextField OVDepositFailText;
private javax.swing.JLabel OVDepositLbl;
private javax.swing.JRadioButton OVDepositPassRb;
private javax.swing.JLabel OVDepositValLbl;
private javax.swing.JLabel OVFailLbl;
private javax.swing.ButtonGroup OVMediaBG;
private javax.swing.JLabel OVMediaCatValLbl;
private javax.swing.JTextField OVMediaFailText;
private javax.swing.JRadioButton OVMediaNumFailRb;
private javax.swing.JLabel OVMediaNumLbl;
private javax.swing.JRadioButton OVMediaNumPassRb;
private javax.swing.ButtonGroup OVNameBG;
private javax.swing.JTextField OVNameFailText;
private javax.swing.JLabel OVNumberLbl;
private javax.swing.JTextField OVOrderIDText;
private javax.swing.JLabel OVOrderNumLbl;
private javax.swing.JLabel OVPassLbl;
private javax.swing.JRadioButton OVPayTypeFailRb;
private javax.swing.JTextField OVPayTypeFailText;
private javax.swing.JLabel OVPayTypePassLbl;
private javax.swing.JRadioButton OVPayTypePassRb;
private javax.swing.JLabel OVPayTypeValLbl;
private javax.swing.ButtonGroup OVPaymentBG;
private javax.swing.JLabel OVReasonLbl;
private javax.swing.JButton OVSearchButton;
private javax.swing.JButton OVSubmitButton;
private javax.swing.JLabel OVVerifyByLbl;
private javax.swing.JTextField OVerIDText;
private javax.swing.JRadioButton OrderAccountPayRB;
private javax.swing.JLabel OrderAssignedToLbl;
private javax.swing.JTextField OrderCUSTIDText;
private javax.swing.JButton OrderClearFieldsButton;
private javax.swing.JLabel OrderContentLbl;
private javax.swing.JTextField OrderContentText;
private javax.swing.JButton OrderCreateBtn;
private javax.swing.JLabel OrderCreatedByLbl;
private javax.swing.JLabel OrderCustNumberLbl;
private javax.swing.JRadioButton OrderDeliverPayRB;
private javax.swing.JLabel OrderDepositLbl;
private javax.swing.JTextField OrderDepositText;
private javax.swing.ButtonGroup OrderEngMediaBG;
private javax.swing.JPanel OrderInfoPanel;
private javax.swing.JLabel OrderMediaCatNumLbl;
private javax.swing.JTextField OrderMediaCatNumText;
private javax.swing.JComboBox OrderMediaStatusCB;
private javax.swing.JLabel OrderMediaStatusLbl;
private javax.swing.JLabel OrderMediaTypeLbl;
private javax.swing.JComboBox OrderNumberCB;
private javax.swing.JLabel OrderNumberLbl;
private javax.swing.ButtonGroup OrderPayTypeBG;
private javax.swing.JLabel OrderPaymentTypeLbl;
private javax.swing.JButton OrderSearchButton;
private javax.swing.JLabel OrderSearchLbl;
private javax.swing.JComboBox OrderStatusCB;
private javax.swing.JLabel OrderStatusLbl;
private javax.swing.JTabbedPane OrderTabbedPane;
private javax.swing.JLabel OrderTotalLbl;
private javax.swing.JTextField OrderTotalText;
private javax.swing.ButtonGroup OrderTypeBG;
private javax.swing.JRadioButton OrderTypePlaqueRB;
private javax.swing.JRadioButton OrderTypeShirtRB;
private javax.swing.JRadioButton OrderTypeTrophyRB;
private javax.swing.JButton OrderUpdateBtn;
private javax.swing.JLabel OrderVerifyByLbl;
private javax.swing.JPanel OrderVerifyPanel;
private javax.swing.JLabel QAAssignedToLbl;
private javax.swing.JLabel QAButtonLbl;
private javax.swing.JButton QAClearButton;
private javax.swing.JLabel QACommentLbl;
private javax.swing.ButtonGroup QAContentBG;
private javax.swing.JRadioButton QAContentCheckFailRb;
private javax.swing.JRadioButton QAContentCheckPassRb;
private javax.swing.JTextField QAContentFailText;
private javax.swing.JLabel QAContentLbl;
private javax.swing.JScrollPane QACorrectiveActionTB;
private javax.swing.JTextArea QACorrectiveActionText;
private javax.swing.JLabel QACreatedByLbl;
private javax.swing.JLabel QAFailCommentLbl;
private javax.swing.JLabel QAFailLbl;
private javax.swing.JLabel QAIDLbl;
private javax.swing.JTextField QAIDText;
private javax.swing.ButtonGroup QAMediaBG;
private javax.swing.JRadioButton QAMediaCheckFailRb;
private javax.swing.JRadioButton QAMediaCheckPassRb;
private javax.swing.JTextField QAMediaFailText;
private javax.swing.ButtonGroup QAMediaFinishBG;
private javax.swing.JRadioButton QAMediaFinishCheckFailRb;
private javax.swing.JRadioButton QAMediaFinishCheckPassRb;
private javax.swing.JTextField QAMediaFinishFailText;
private javax.swing.JLabel QAMediaFinishLbl;
private javax.swing.JLabel QAMediaLbl;
private javax.swing.JLabel QAOrderIDLbl;
private javax.swing.JTextField QAOrderIDText;
private javax.swing.JPanel QAPanel;
private javax.swing.JLabel QAPassLbl;
private javax.swing.JButton QASearchButton;
private javax.swing.JButton QASubmitButton;
private javax.swing.JLabel QAVerifiedByLbl;
private javax.swing.ButtonGroup QAWorkmanshipBG;
private javax.swing.JRadioButton QAWorkmanshipCheckFailRb;
private javax.swing.JRadioButton QAWorkmanshipCheckPassRb;
private javax.swing.JTextField QAWorkmanshipFailText;
private javax.swing.JLabel QAWorkmanshipLbl;
private javax.swing.JTabbedPane WSCInterface;
private javax.swing.JList custOrdLst;
private javax.swing.JList emOrdersLst;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
protected javax.swing.JLabel lblLoginStatus;
// End of variables declaration//GEN-END:variables
//</editor-fold>
}
|
diff --git a/src/cm/aptoide/pt2/services/ServiceDownload.java b/src/cm/aptoide/pt2/services/ServiceDownload.java
index f022fac5..a9d9af07 100644
--- a/src/cm/aptoide/pt2/services/ServiceDownload.java
+++ b/src/cm/aptoide/pt2/services/ServiceDownload.java
@@ -1,318 +1,318 @@
/*
* ServiceDownload, part of Aptoide
* Copyright (C) 2012 Duarte Silveira
* [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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package cm.aptoide.pt2.services;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import cm.aptoide.pt2.exceptions.AptoideExceptionDownload;
import cm.aptoide.pt2.exceptions.AptoideExceptionNotFound;
import cm.aptoide.pt2.views.ViewCache;
import cm.aptoide.pt2.views.ViewDownload;
import cm.aptoide.pt2.views.ViewLogin;
/**
* ServiceDownload
*
* @author dsilveira
*
*/
public class ServiceDownload extends Service {
// This is the object that receives interactions from service clients.
private final IBinder binder = new ServiceDownloadBinder();
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class ServiceDownloadBinder extends Binder {
public ServiceDownload getService() {
return ServiceDownload.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.d("Aptoide-ServiceDownload", "Bound");
return binder;
}
private static Handler progressUpdateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
//update msg.what object id
}
};
private DownloadManager downloadManager;
private class DownloadManager{
private ExecutorService installedColectorsPool;
public DownloadManager(){
installedColectorsPool = Executors.newSingleThreadExecutor();
}
public void downloadApk(ViewDownload download, ViewCache cache){
downloadApk(download, cache, null);
}
public void downloadApk(ViewDownload download, ViewCache cache, ViewLogin login){
try {
installedColectorsPool.execute(new DownloadApk(download, cache, login));
} catch (Exception e) { }
}
private class DownloadApk implements Runnable{
ViewDownload download;
ViewCache cache;
ViewLogin login;
public DownloadApk(ViewDownload download, ViewCache cache, ViewLogin login) {
this.download = download;
this.cache = cache;
this.login = login;
}
@Override
public void run() {
// Log.d("Aptoide-ManagerDownloads", "apk download: "+download.getCache());
if(!cache.isCached() || !cache.checkMd5()){
try {
download(download, cache, login);
} catch (Exception e) {
try {
download(download, cache, login);
} catch (Exception e2) {
download(download, cache, login);
}
}
}
Log.d("Aptoide-ManagerDownloads", "apk download: "+download.getRemotePath());
}
}
}
@Override
public void onCreate() {
downloadManager = new DownloadManager();
super.onCreate();
}
// private
// private String getUserAgentString(){
// ViewClientStatistics clientStatistics = getClientStatistics();
// return String.format(Constants.USER_AGENT_FORMAT
// , clientStatistics.getAptoideVersionNameInUse(), clientStatistics.getScreenDimensions().getFormattedString()
// , clientStatistics.getAptoideClientUUID(), getServerUsername());
// }
public void installApp(ViewCache apk){
// if(isAppScheduledToInstall(appHashid)){
// unscheduleInstallApp(appHashid);
// }
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(Uri.fromFile(apk.getFile()),"application/vnd.android.package-archive");
Log.d("Aptoide", "Installing app: "+apk.getLocalPath());
startActivity(install);
}
public void downloadApk(ViewDownload download, ViewCache cache){
downloadManager.downloadApk(download, cache);
}
public void downloadApk(ViewDownload download, ViewCache cache, ViewLogin login){
downloadManager.downloadApk(download, cache, login);
}
private void download(ViewDownload download, ViewCache cache, ViewLogin login){
boolean overwriteCache = false;
boolean resuming = false;
boolean isLoginRequired = (login != null);
String localPath = cache.getLocalPath();
String remotePath = download.getRemotePath();
long targetBytes;
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(localPath, !overwriteCache);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remotePath);
Log.d("Aptoide-download","downloading from: "+remotePath+" to: "+localPath);
// Log.d("Aptoide-download","downloading with: "+getUserAgentString());
Log.d("Aptoide-download","downloading mode private: "+isLoginRequired);
// httpGet.setHeader("User-Agent", getUserAgentString());
long resumeLength = cache.getFileLength();
if(!overwriteCache){
if(resumeLength > 0){
resuming = true;
}
Log.d("Aptoide-download","downloading from [bytes]: "+resumeLength);
httpGet.setHeader("Range", "bytes="+resumeLength+"-");
download.setProgress(resumeLength);
}
if(isLoginRequired){
URL url = new URL(remotePath);
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(url.getHost(), url.getPort()),
new UsernamePasswordCredentials(login.getUsername(), login.getPassword()));
}
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Problem in network... retry...");
httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Major network exception... Exiting!");
/*msg_al.arg1= 1;
download_error_handler.sendMessage(msg_al);*/
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}
}
if(httpResponse.getStatusLine().getStatusCode() == 401){
Log.d("Aptoide-ManagerDownloads","401 Timed out!");
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}else if(httpResponse.getStatusLine().getStatusCode() == 404){
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new AptoideExceptionNotFound("404 Not found!");
}else{
// Log.d("Aptoide-ManagerDownloads", "Download target size: "+notification.getProgressCompletionTarget());
// if(download.isSizeKnown()){
// targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes
// notification.setProgressCompletionTarget(targetBytes);
// }else{
- if(httpResponse.containsHeader("Content-Length") && resumeLength != 0){
+ if(httpResponse.containsHeader("Content-Length")){
targetBytes = Long.parseLong(httpResponse.getFirstHeader("Content-Length").getValue());
Log.d("Aptoide-ManagerDownloads","Download targetBytes: "+targetBytes);
download.setProgressTarget(targetBytes);
}
// }
InputStream inputStream= null;
if((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))){
Log.d("Aptoide-ManagerDownloads","with gzip");
inputStream = new GZIPInputStream(httpResponse.getEntity().getContent());
}else{
// Log.d("Aptoide-ManagerDownloads","No gzip");
inputStream = httpResponse.getEntity().getContent();
}
byte data[] = new byte[8096];
/** in percentage */
int progressTrigger = 5;
int bytesRead;
while((bytesRead = inputStream.read(data, 0, 8096)) > 0) {
download.incrementProgress(bytesRead);
fileOutputStream.write(data,0,bytesRead);
if(download.getProgressPercentage() % progressTrigger == 0){
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
}
}
Log.d("Aptoide-ManagerDownloads","Download done! Name: "+download.getRemotePath()+" localPath: "+localPath);
download.setCompleted();
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
if(cache.hasMd5Sum()){
if(!cache.checkMd5()){
cache.clearCache();
throw new AptoideExceptionDownload("md5 check failed!");
}
}
installApp(cache);
}
}catch (Exception e) {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e1) { }
e.printStackTrace();
if(cache.getFileLength() > 0){
download.setCompleted();
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
// scheduleInstallApp(cache.getId());
}
throw new AptoideExceptionDownload(e);
}
}
}
| true | true | private void download(ViewDownload download, ViewCache cache, ViewLogin login){
boolean overwriteCache = false;
boolean resuming = false;
boolean isLoginRequired = (login != null);
String localPath = cache.getLocalPath();
String remotePath = download.getRemotePath();
long targetBytes;
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(localPath, !overwriteCache);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remotePath);
Log.d("Aptoide-download","downloading from: "+remotePath+" to: "+localPath);
// Log.d("Aptoide-download","downloading with: "+getUserAgentString());
Log.d("Aptoide-download","downloading mode private: "+isLoginRequired);
// httpGet.setHeader("User-Agent", getUserAgentString());
long resumeLength = cache.getFileLength();
if(!overwriteCache){
if(resumeLength > 0){
resuming = true;
}
Log.d("Aptoide-download","downloading from [bytes]: "+resumeLength);
httpGet.setHeader("Range", "bytes="+resumeLength+"-");
download.setProgress(resumeLength);
}
if(isLoginRequired){
URL url = new URL(remotePath);
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(url.getHost(), url.getPort()),
new UsernamePasswordCredentials(login.getUsername(), login.getPassword()));
}
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Problem in network... retry...");
httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Major network exception... Exiting!");
/*msg_al.arg1= 1;
download_error_handler.sendMessage(msg_al);*/
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}
}
if(httpResponse.getStatusLine().getStatusCode() == 401){
Log.d("Aptoide-ManagerDownloads","401 Timed out!");
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}else if(httpResponse.getStatusLine().getStatusCode() == 404){
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new AptoideExceptionNotFound("404 Not found!");
}else{
// Log.d("Aptoide-ManagerDownloads", "Download target size: "+notification.getProgressCompletionTarget());
// if(download.isSizeKnown()){
// targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes
// notification.setProgressCompletionTarget(targetBytes);
// }else{
if(httpResponse.containsHeader("Content-Length") && resumeLength != 0){
targetBytes = Long.parseLong(httpResponse.getFirstHeader("Content-Length").getValue());
Log.d("Aptoide-ManagerDownloads","Download targetBytes: "+targetBytes);
download.setProgressTarget(targetBytes);
}
// }
InputStream inputStream= null;
if((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))){
Log.d("Aptoide-ManagerDownloads","with gzip");
inputStream = new GZIPInputStream(httpResponse.getEntity().getContent());
}else{
// Log.d("Aptoide-ManagerDownloads","No gzip");
inputStream = httpResponse.getEntity().getContent();
}
byte data[] = new byte[8096];
/** in percentage */
int progressTrigger = 5;
int bytesRead;
while((bytesRead = inputStream.read(data, 0, 8096)) > 0) {
download.incrementProgress(bytesRead);
fileOutputStream.write(data,0,bytesRead);
if(download.getProgressPercentage() % progressTrigger == 0){
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
}
}
Log.d("Aptoide-ManagerDownloads","Download done! Name: "+download.getRemotePath()+" localPath: "+localPath);
download.setCompleted();
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
if(cache.hasMd5Sum()){
if(!cache.checkMd5()){
cache.clearCache();
throw new AptoideExceptionDownload("md5 check failed!");
}
}
installApp(cache);
}
}catch (Exception e) {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e1) { }
e.printStackTrace();
if(cache.getFileLength() > 0){
download.setCompleted();
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
// scheduleInstallApp(cache.getId());
}
throw new AptoideExceptionDownload(e);
}
}
| private void download(ViewDownload download, ViewCache cache, ViewLogin login){
boolean overwriteCache = false;
boolean resuming = false;
boolean isLoginRequired = (login != null);
String localPath = cache.getLocalPath();
String remotePath = download.getRemotePath();
long targetBytes;
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(localPath, !overwriteCache);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remotePath);
Log.d("Aptoide-download","downloading from: "+remotePath+" to: "+localPath);
// Log.d("Aptoide-download","downloading with: "+getUserAgentString());
Log.d("Aptoide-download","downloading mode private: "+isLoginRequired);
// httpGet.setHeader("User-Agent", getUserAgentString());
long resumeLength = cache.getFileLength();
if(!overwriteCache){
if(resumeLength > 0){
resuming = true;
}
Log.d("Aptoide-download","downloading from [bytes]: "+resumeLength);
httpGet.setHeader("Range", "bytes="+resumeLength+"-");
download.setProgress(resumeLength);
}
if(isLoginRequired){
URL url = new URL(remotePath);
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(url.getHost(), url.getPort()),
new UsernamePasswordCredentials(login.getUsername(), login.getPassword()));
}
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Problem in network... retry...");
httpResponse = httpClient.execute(httpGet);
if(httpResponse == null){
Log.d("Aptoide-ManagerDownloads","Major network exception... Exiting!");
/*msg_al.arg1= 1;
download_error_handler.sendMessage(msg_al);*/
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}
}
if(httpResponse.getStatusLine().getStatusCode() == 401){
Log.d("Aptoide-ManagerDownloads","401 Timed out!");
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new TimeoutException();
}else if(httpResponse.getStatusLine().getStatusCode() == 404){
fileOutputStream.close();
if(!resuming){
cache.clearCache();
}
throw new AptoideExceptionNotFound("404 Not found!");
}else{
// Log.d("Aptoide-ManagerDownloads", "Download target size: "+notification.getProgressCompletionTarget());
// if(download.isSizeKnown()){
// targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes
// notification.setProgressCompletionTarget(targetBytes);
// }else{
if(httpResponse.containsHeader("Content-Length")){
targetBytes = Long.parseLong(httpResponse.getFirstHeader("Content-Length").getValue());
Log.d("Aptoide-ManagerDownloads","Download targetBytes: "+targetBytes);
download.setProgressTarget(targetBytes);
}
// }
InputStream inputStream= null;
if((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))){
Log.d("Aptoide-ManagerDownloads","with gzip");
inputStream = new GZIPInputStream(httpResponse.getEntity().getContent());
}else{
// Log.d("Aptoide-ManagerDownloads","No gzip");
inputStream = httpResponse.getEntity().getContent();
}
byte data[] = new byte[8096];
/** in percentage */
int progressTrigger = 5;
int bytesRead;
while((bytesRead = inputStream.read(data, 0, 8096)) > 0) {
download.incrementProgress(bytesRead);
fileOutputStream.write(data,0,bytesRead);
if(download.getProgressPercentage() % progressTrigger == 0){
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
}
}
Log.d("Aptoide-ManagerDownloads","Download done! Name: "+download.getRemotePath()+" localPath: "+localPath);
download.setCompleted();
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
if(cache.hasMd5Sum()){
if(!cache.checkMd5()){
cache.clearCache();
throw new AptoideExceptionDownload("md5 check failed!");
}
}
installApp(cache);
}
}catch (Exception e) {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e1) { }
e.printStackTrace();
if(cache.getFileLength() > 0){
download.setCompleted();
progressUpdateHandler.sendEmptyMessage(cache.hashCode());
// scheduleInstallApp(cache.getId());
}
throw new AptoideExceptionDownload(e);
}
}
|
diff --git a/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyPerRequestTimeoutTest.java b/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyPerRequestTimeoutTest.java
index 5e1ea2235..c9b4707df 100644
--- a/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyPerRequestTimeoutTest.java
+++ b/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyPerRequestTimeoutTest.java
@@ -1,32 +1,32 @@
/*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.providers.netty;
import static org.testng.Assert.*;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.async.PerRequestTimeoutTest;
public class NettyPerRequestTimeoutTest extends PerRequestTimeoutTest {
@Override
protected void checkTimeoutMessage(String message) {
- assertTrue(message.startsWith("Request reached timeout of 100 ms after "));
+ assertTrue(message.equals("Request timeout of 100 ms"));
}
@Override
public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
return NettyProviderUtil.nettyProvider(config);
}
}
| true | true | protected void checkTimeoutMessage(String message) {
assertTrue(message.startsWith("Request reached timeout of 100 ms after "));
}
| protected void checkTimeoutMessage(String message) {
assertTrue(message.equals("Request timeout of 100 ms"));
}
|
diff --git a/src/com/modcrafting/diablodrops/sets/SetsAPI.java b/src/com/modcrafting/diablodrops/sets/SetsAPI.java
index 835caee..b7aab85 100644
--- a/src/com/modcrafting/diablodrops/sets/SetsAPI.java
+++ b/src/com/modcrafting/diablodrops/sets/SetsAPI.java
@@ -1,143 +1,145 @@
package com.modcrafting.diablodrops.sets;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.DiabloDrops;
public class SetsAPI
{
private final Random gen;
private final DiabloDrops plugin;
public SetsAPI(final DiabloDrops instance)
{
plugin = instance;
gen = plugin.gen;
}
/**
* Gets the armor set represented by name
*
* @param name
* of set
* @return armor set
*/
public ArmorSet getArmorSet(final String name)
{
for (ArmorSet as : plugin.armorSets)
{
if (as.getName().equalsIgnoreCase(name))
return as;
}
return null;
}
public Random getGen()
{
return gen;
}
/**
* Gets the name of the set a player could be wearing
*
* @param player
* Player to check
* @return name of the set
*/
public String getNameOfSet(final LivingEntity entity)
{
ItemStack his = entity.getEquipment().getHelmet();
if (his == null)
return null;
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
return ss[0];
}
public DiabloDrops getPlugin()
{
return plugin;
}
public boolean wearingSet(final LivingEntity entity)
{
ItemStack his = entity.getEquipment().getHelmet();
ItemStack cis = entity.getEquipment().getChestplate();
ItemStack lis = entity.getEquipment().getLeggings();
ItemStack bis = entity.getEquipment().getBoots();
if ((his == null) || (cis == null) || (lis == null) || (bis == null))
return false;
Set<ItemStack> sis = new HashSet<ItemStack>();
sis.add(cis);
sis.add(lis);
sis.add(bis);
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
String potentialSet = ss[0];
for (ItemStack is : sis)
{
ItemMeta ism = is.getItemMeta();
- String[] splits = ChatColor.stripColor(ism.getDisplayName()).split(" ");
- if (!splits[0].equalsIgnoreCase(potentialSet))
- return false;
+ if(ism.getDisplayName()!=null){
+ String[] splits = ChatColor.stripColor(ism.getDisplayName()).split(" ");
+ if (!splits[0].equalsIgnoreCase(potentialSet))
+ return false;
+ }
}
return true;
}
/**
* Is player wearing a set of matching armor?
*
* @param player
* @return is set
*/
public boolean wearingSet(final Player player)
{
ItemStack his = player.getInventory().getHelmet();
ItemStack cis = player.getInventory().getChestplate();
ItemStack lis = player.getInventory().getLeggings();
ItemStack bis = player.getInventory().getBoots();
if ((his == null) || (cis == null) || (lis == null) || (bis == null))
return false;
Set<ItemStack> sis = new HashSet<ItemStack>();
sis.add(cis);
sis.add(lis);
sis.add(bis);
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
String potentialSet = ss[0];
for (ItemStack is : sis)
{
ItemMeta ism = is.getItemMeta();
String[] splits = ChatColor.stripColor(ism.getDisplayName()).split(" ");
if (!splits[0].equalsIgnoreCase(potentialSet))
return false;
}
return true;
}
/**
* Gets the name of the set a player could be wearing
*
* @param player
* Player to check
* @return name of the set
*/
public String getNameOfSet(Player player)
{
ItemStack his = player.getInventory().getHelmet();
if (his == null)
return null;
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
return ss[0];
}
}
| true | true | public boolean wearingSet(final LivingEntity entity)
{
ItemStack his = entity.getEquipment().getHelmet();
ItemStack cis = entity.getEquipment().getChestplate();
ItemStack lis = entity.getEquipment().getLeggings();
ItemStack bis = entity.getEquipment().getBoots();
if ((his == null) || (cis == null) || (lis == null) || (bis == null))
return false;
Set<ItemStack> sis = new HashSet<ItemStack>();
sis.add(cis);
sis.add(lis);
sis.add(bis);
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
String potentialSet = ss[0];
for (ItemStack is : sis)
{
ItemMeta ism = is.getItemMeta();
String[] splits = ChatColor.stripColor(ism.getDisplayName()).split(" ");
if (!splits[0].equalsIgnoreCase(potentialSet))
return false;
}
return true;
}
| public boolean wearingSet(final LivingEntity entity)
{
ItemStack his = entity.getEquipment().getHelmet();
ItemStack cis = entity.getEquipment().getChestplate();
ItemStack lis = entity.getEquipment().getLeggings();
ItemStack bis = entity.getEquipment().getBoots();
if ((his == null) || (cis == null) || (lis == null) || (bis == null))
return false;
Set<ItemStack> sis = new HashSet<ItemStack>();
sis.add(cis);
sis.add(lis);
sis.add(bis);
ItemMeta meta = his.getItemMeta();
String[] ss = ChatColor.stripColor(meta.getDisplayName()).split(" ");
String potentialSet = ss[0];
for (ItemStack is : sis)
{
ItemMeta ism = is.getItemMeta();
if(ism.getDisplayName()!=null){
String[] splits = ChatColor.stripColor(ism.getDisplayName()).split(" ");
if (!splits[0].equalsIgnoreCase(potentialSet))
return false;
}
}
return true;
}
|
diff --git a/src/java/org/infoglue/cms/applications/common/actions/SimpleXmlServiceAction.java b/src/java/org/infoglue/cms/applications/common/actions/SimpleXmlServiceAction.java
index 25150c4c0..4776f2006 100755
--- a/src/java/org/infoglue/cms/applications/common/actions/SimpleXmlServiceAction.java
+++ b/src/java/org/infoglue/cms/applications/common/actions/SimpleXmlServiceAction.java
@@ -1,421 +1,423 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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.
*
* ===============================================================================
*/
/**
* @author Stefan Sik
* @since 1.4
*/
package org.infoglue.cms.applications.common.actions;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.infoglue.cms.applications.common.VisualFormatter;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.controllers.kernel.impl.simple.LanguageController;
import org.infoglue.cms.controllers.kernel.impl.simple.RepositoryController;
import org.infoglue.cms.controllers.kernel.impl.simple.TransactionHistoryController;
import org.infoglue.cms.entities.content.ContentVersionVO;
import org.infoglue.cms.entities.kernel.BaseEntityVO;
import org.infoglue.cms.entities.management.ContentTypeDefinition;
import org.infoglue.cms.entities.management.ContentTypeDefinitionVO;
import org.infoglue.cms.entities.management.RepositoryVO;
import org.infoglue.cms.entities.management.TransactionHistoryVO;
import org.infoglue.cms.entities.management.impl.simple.ContentTypeDefinitionImpl;
import org.infoglue.cms.exception.ConstraintException;
import org.infoglue.cms.exception.SystemException;
import org.infoglue.cms.security.InfoGluePrincipal;
import com.frovi.ss.Tree.BaseNode;
import com.frovi.ss.Tree.INodeSupplier;
public abstract class SimpleXmlServiceAction extends WebworkAbstractAction
{
// protected static String ENCODING = "ISO-8859-1";
protected static String ENCODING = "UTF-8";
protected static String TYPE_FOLDER = "Folder";
protected static String TYPE_ITEM = "Item";
protected static String TYPE_REPOSITORY = "Repository";
protected String showLeafs = "yes";
protected Integer parent = null;
protected Integer repositoryId = null;
protected String urlArgSeparator = "&";
protected String action = "";
protected boolean createAction = false;
protected boolean useTemplate = false;
protected VisualFormatter formatter = new VisualFormatter();
protected String[] allowedContentTypeNames = null;
public abstract INodeSupplier getNodeSupplier() throws SystemException;
protected abstract BaseEntityVO getRootEntityVO(Integer repositoryId, InfoGluePrincipal principal) throws ConstraintException, SystemException;
public List getContentTypeDefinitions() throws Exception
{
return ContentTypeDefinitionController.getController().getContentTypeDefinitionVOList();
}
private String encode(String text)
{
return text;
}
protected String makeAction(BaseNode node) throws UnsupportedEncodingException
{
String action = "javascript:onTreeItemClick(this,";
//action+="'" + node.getId() + "','" + repositoryId + "','" + URLEncoder.encode(node.getTitle(),ENCODING) + "');";
//action+="'" + node.getId() + "','" + repositoryId + "','" + new VisualFormatter().escapeForAdvancedJavascripts(node.getTitle()) + "');";
action+="'" + node.getId() + "','" + repositoryId + "','" + new VisualFormatter().escapeForAdvancedJavascripts(node.getTitle()) + "');";
//System.out.println("action:" + action);
return action;
}
protected String getFormattedDocument(Document doc)
{
return getFormattedDocument(doc, true);
}
protected String getFormattedDocument(Document doc, boolean compact)
{
OutputFormat format = compact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
format.setEncoding(ENCODING);
format.setExpandEmptyElements(false);
StringWriter stringWriter = new StringWriter();
XMLWriter writer = new XMLWriter(stringWriter, format);
try
{
writer.write(doc);
}
catch (IOException e)
{
e.printStackTrace();
}
return stringWriter.toString();
}
protected String out(String string) throws IOException
{
getResponse().setContentType("text/xml; charset=" + ENCODING);
// getResponse().setContentLength(string.length());
/*OutputStream outs = getResponse().getOutputStream();
outs.write(string.getBytes());
outs.flush();
outs.close();*/
PrintWriter out = getResponse().getWriter();
out.println(string);
// out.write(new String(string.getBytes(), ENCODING));
return null;
}
/*
* Returns all Languages for a given repository (repositoryId)
*/
public String doLanguage() throws Exception
{
return null;
}
/*
* Returns all contentTypeDefinitions
*/
public String doContentTypeDefinitions() throws Exception
{
List contentTypeDefinitions = getContentTypeDefinitions();
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("definitions");
TransactionHistoryController transactionHistoryController = TransactionHistoryController.getController();
for(Iterator i=contentTypeDefinitions.iterator();i.hasNext();)
{
ContentTypeDefinitionVO vo = (ContentTypeDefinitionVO) i.next();
if(vo.getType().compareTo(ContentTypeDefinitionVO.CONTENT)==0)
{
TransactionHistoryVO transactionHistoryVO = transactionHistoryController.getLatestTransactionHistoryVOForEntity(ContentTypeDefinitionImpl.class, vo.getContentTypeDefinitionId());
Element definition = DocumentHelper.createElement("definition");
definition
.addAttribute("id", "" + vo.getContentTypeDefinitionId())
.addAttribute("type", "" + vo.getType())
.addAttribute("name", vo.getName())
;
if(transactionHistoryVO!=null)
definition.addAttribute("mod", formatDate(transactionHistoryVO.getTransactionDateTime()));
Element schemaValue = definition.addElement("schemaValue");
schemaValue.addCDATA(vo.getSchemaValue());
root.add(definition);
}
}
return out(getFormattedDocument(doc));
}
protected String formatDate(Date date)
{
return "" + date;
}
/*
* Main action, returns the content tree
*/
public String doExecute() throws Exception
{
if (useTemplate) return "success";
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("tree");
INodeSupplier sup;
if(repositoryId == null)
{
List repositories = RepositoryController.getController().getAuthorizedRepositoryVOList(this.getInfoGluePrincipal());
for(Iterator i=repositories.iterator();i.hasNext();)
{
RepositoryVO r = (RepositoryVO) i.next();
BaseEntityVO entityVO = getRootEntityVO(r.getId(), this.getInfoGluePrincipal());
String src= action + "?repositoryId=" + r.getId() + urlArgSeparator + "parent=" + entityVO.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString1:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src1:" + src);
String text=r.getName();
Element element = root.addElement("tree");
element
.addAttribute("id", "" + r.getId())
.addAttribute("repositoryId", "" + r.getId())
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", TYPE_REPOSITORY);
}
out(getFormattedDocument(doc));
return null;
}
sup = getNodeSupplier();
if(parent == null)
{
BaseNode node = sup.getRootNode();
String text = node.getTitle();
String type = TYPE_FOLDER;
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + node.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString2:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src2:" + src);
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + node.getId())
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", type);
out(getFormattedDocument(doc));
return null;
}
if(parent.intValue() > -1)
{
Collection containerNodes = sup.getChildContainerNodes(parent);
Collection childNodes = sup.getChildLeafNodes(parent);
ContentController contentController = ContentController.getContentController();
ContentVersionController contentVersionController = ContentVersionController.getContentVersionController();
Iterator it = containerNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
if (theNode.isContainer() && sup.hasChildren())
{
theNode.setChildren(sup.hasChildren(theNode.getId()));
}
// String src = theNode.hasChildren() ? action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId(): "";
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(createAction && src.length() >0) src += urlArgSeparator + "showLeafs=" + showLeafs;
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(theNode.getTitle()))
.addAttribute("src", src)
.addAttribute("type", TYPE_FOLDER)
.addAttribute("hasChildren", "" + theNode.hasChildren());
if(createAction) elm.addAttribute("action", makeAction(theNode));
}
it = childNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
String text = theNode.getTitle();
String action = makeAction(theNode);
String type = TYPE_ITEM;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("type", type)
;
if(createAction)
elm.addAttribute("action", action);
else
{
ContentVersionVO activeVersion = contentVersionController.getLatestActiveContentVersionVO(theNode.getId(), LanguageController.getController().getMasterLanguage(repositoryId).getLanguageId());
if(activeVersion!=null && !useTemplate)
elm.addAttribute("activeVersion", "" + activeVersion.getContentVersionId());
}
- if(!useTemplate)
+ //System.out.println("SupplierClass:" + sup.getClass().getName());
+ //TODO - this was a quickfix only
+ if(!useTemplate && sup.getClass().getName().indexOf("Content") > -1)
{
ContentTypeDefinitionVO contentTypeDefinitionVO = contentController.getContentTypeDefinition(theNode.getId());
if(contentTypeDefinitionVO != null)
elm.addAttribute("contentTypeId","" + contentTypeDefinitionVO.getContentTypeDefinitionId());
}
}
out(getFormattedDocument(doc));
return null;
}
return null;
}
public Integer getParent() {
return parent;
}
public void setParent(Integer integer) {
parent = integer;
}
public Integer getRepositoryId() {
return repositoryId;
}
public void setRepositoryId(Integer integer) {
repositoryId = integer;
}
public boolean isCreateAction()
{
return createAction;
}
public void setCreateAction(boolean createAction)
{
this.createAction = createAction;
}
public boolean isUseTemplate()
{
return useTemplate;
}
public void setUseTemplate(boolean useTemplate)
{
this.useTemplate = useTemplate;
}
public String getAction()
{
return action;
}
public void setAction(String action)
{
this.action = action;
}
public String getShowLeafs() {
return showLeafs;
}
public void setShowLeafs(String showLeafs) {
this.showLeafs = showLeafs;
}
public String[] getAllowedContentTypeNames()
{
return allowedContentTypeNames;
}
public void setAllowedContentTypeNames(String[] allowedContentTypeNames)
{
this.allowedContentTypeNames = allowedContentTypeNames;
}
public String getAllowedContentTypeNamesAsUrlEncodedString() throws Exception
{
if(allowedContentTypeNames == null)
return "";
StringBuffer sb = new StringBuffer();
for(int i=0; i<allowedContentTypeNames.length; i++)
{
if(i > 0)
sb.append("&");
sb.append("allowedContentTypeNames=" + URLEncoder.encode(allowedContentTypeNames[i], "UTF-8"));
}
return sb.toString();
}
}
| true | true | public String doExecute() throws Exception
{
if (useTemplate) return "success";
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("tree");
INodeSupplier sup;
if(repositoryId == null)
{
List repositories = RepositoryController.getController().getAuthorizedRepositoryVOList(this.getInfoGluePrincipal());
for(Iterator i=repositories.iterator();i.hasNext();)
{
RepositoryVO r = (RepositoryVO) i.next();
BaseEntityVO entityVO = getRootEntityVO(r.getId(), this.getInfoGluePrincipal());
String src= action + "?repositoryId=" + r.getId() + urlArgSeparator + "parent=" + entityVO.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString1:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src1:" + src);
String text=r.getName();
Element element = root.addElement("tree");
element
.addAttribute("id", "" + r.getId())
.addAttribute("repositoryId", "" + r.getId())
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", TYPE_REPOSITORY);
}
out(getFormattedDocument(doc));
return null;
}
sup = getNodeSupplier();
if(parent == null)
{
BaseNode node = sup.getRootNode();
String text = node.getTitle();
String type = TYPE_FOLDER;
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + node.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString2:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src2:" + src);
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + node.getId())
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", type);
out(getFormattedDocument(doc));
return null;
}
if(parent.intValue() > -1)
{
Collection containerNodes = sup.getChildContainerNodes(parent);
Collection childNodes = sup.getChildLeafNodes(parent);
ContentController contentController = ContentController.getContentController();
ContentVersionController contentVersionController = ContentVersionController.getContentVersionController();
Iterator it = containerNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
if (theNode.isContainer() && sup.hasChildren())
{
theNode.setChildren(sup.hasChildren(theNode.getId()));
}
// String src = theNode.hasChildren() ? action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId(): "";
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(createAction && src.length() >0) src += urlArgSeparator + "showLeafs=" + showLeafs;
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(theNode.getTitle()))
.addAttribute("src", src)
.addAttribute("type", TYPE_FOLDER)
.addAttribute("hasChildren", "" + theNode.hasChildren());
if(createAction) elm.addAttribute("action", makeAction(theNode));
}
it = childNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
String text = theNode.getTitle();
String action = makeAction(theNode);
String type = TYPE_ITEM;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("type", type)
;
if(createAction)
elm.addAttribute("action", action);
else
{
ContentVersionVO activeVersion = contentVersionController.getLatestActiveContentVersionVO(theNode.getId(), LanguageController.getController().getMasterLanguage(repositoryId).getLanguageId());
if(activeVersion!=null && !useTemplate)
elm.addAttribute("activeVersion", "" + activeVersion.getContentVersionId());
}
if(!useTemplate)
{
ContentTypeDefinitionVO contentTypeDefinitionVO = contentController.getContentTypeDefinition(theNode.getId());
if(contentTypeDefinitionVO != null)
elm.addAttribute("contentTypeId","" + contentTypeDefinitionVO.getContentTypeDefinitionId());
}
}
out(getFormattedDocument(doc));
return null;
}
return null;
}
| public String doExecute() throws Exception
{
if (useTemplate) return "success";
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("tree");
INodeSupplier sup;
if(repositoryId == null)
{
List repositories = RepositoryController.getController().getAuthorizedRepositoryVOList(this.getInfoGluePrincipal());
for(Iterator i=repositories.iterator();i.hasNext();)
{
RepositoryVO r = (RepositoryVO) i.next();
BaseEntityVO entityVO = getRootEntityVO(r.getId(), this.getInfoGluePrincipal());
String src= action + "?repositoryId=" + r.getId() + urlArgSeparator + "parent=" + entityVO.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString1:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src1:" + src);
String text=r.getName();
Element element = root.addElement("tree");
element
.addAttribute("id", "" + r.getId())
.addAttribute("repositoryId", "" + r.getId())
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", TYPE_REPOSITORY);
}
out(getFormattedDocument(doc));
return null;
}
sup = getNodeSupplier();
if(parent == null)
{
BaseNode node = sup.getRootNode();
String text = node.getTitle();
String type = TYPE_FOLDER;
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + node.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
System.out.println("allowedContentTypeNamesUrlEncodedString2:" + allowedContentTypeNamesUrlEncodedString);
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
System.out.println("src2:" + src);
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + node.getId())
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("src", src)
.addAttribute("hasChildren", "true")
.addAttribute("type", type);
out(getFormattedDocument(doc));
return null;
}
if(parent.intValue() > -1)
{
Collection containerNodes = sup.getChildContainerNodes(parent);
Collection childNodes = sup.getChildLeafNodes(parent);
ContentController contentController = ContentController.getContentController();
ContentVersionController contentVersionController = ContentVersionController.getContentVersionController();
Iterator it = containerNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
if (theNode.isContainer() && sup.hasChildren())
{
theNode.setChildren(sup.hasChildren(theNode.getId()));
}
// String src = theNode.hasChildren() ? action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId(): "";
String src = action + "?repositoryId=" + repositoryId + urlArgSeparator + "parent=" + theNode.getId();
if(createAction && src.length() >0) src += urlArgSeparator + "createAction=true";
if(createAction && src.length() >0) src += urlArgSeparator + "showLeafs=" + showLeafs;
if(action.length()>0 && src.length() >0) src += urlArgSeparator + "action=" + action;
String allowedContentTypeNamesUrlEncodedString = getAllowedContentTypeNamesAsUrlEncodedString();
if(allowedContentTypeNamesUrlEncodedString.length()>0 && src.length() >0) src += urlArgSeparator + allowedContentTypeNamesUrlEncodedString;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(theNode.getTitle()))
.addAttribute("src", src)
.addAttribute("type", TYPE_FOLDER)
.addAttribute("hasChildren", "" + theNode.hasChildren());
if(createAction) elm.addAttribute("action", makeAction(theNode));
}
it = childNodes.iterator();
while (it.hasNext())
{
BaseNode theNode = (BaseNode) it.next();
String text = theNode.getTitle();
String action = makeAction(theNode);
String type = TYPE_ITEM;
Element elm = root.addElement("tree");
elm
.addAttribute("id", "" + theNode.getId())
.addAttribute("parent", "" + parent)
.addAttribute("repositoryId", "" + repositoryId)
.addAttribute("text", encode(text))
.addAttribute("type", type)
;
if(createAction)
elm.addAttribute("action", action);
else
{
ContentVersionVO activeVersion = contentVersionController.getLatestActiveContentVersionVO(theNode.getId(), LanguageController.getController().getMasterLanguage(repositoryId).getLanguageId());
if(activeVersion!=null && !useTemplate)
elm.addAttribute("activeVersion", "" + activeVersion.getContentVersionId());
}
//System.out.println("SupplierClass:" + sup.getClass().getName());
//TODO - this was a quickfix only
if(!useTemplate && sup.getClass().getName().indexOf("Content") > -1)
{
ContentTypeDefinitionVO contentTypeDefinitionVO = contentController.getContentTypeDefinition(theNode.getId());
if(contentTypeDefinitionVO != null)
elm.addAttribute("contentTypeId","" + contentTypeDefinitionVO.getContentTypeDefinitionId());
}
}
out(getFormattedDocument(doc));
return null;
}
return null;
}
|
diff --git a/src/at/ac/tuwien/lsdc/csvGenerator/CsvGenerator.java b/src/at/ac/tuwien/lsdc/csvGenerator/CsvGenerator.java
index 190a83d..58c5099 100644
--- a/src/at/ac/tuwien/lsdc/csvGenerator/CsvGenerator.java
+++ b/src/at/ac/tuwien/lsdc/csvGenerator/CsvGenerator.java
@@ -1,76 +1,76 @@
package at.ac.tuwien.lsdc.csvGenerator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.random.JDKRandomGenerator;
import org.apache.commons.math3.random.RandomData;
import org.apache.commons.math3.random.RandomDataImpl;
import at.ac.tuwien.lsdc.generator.Request;
import at.ac.tuwien.lsdc.generator.RequestGenerator;
public class CsvGenerator {
public static void main(String args[]) throws IOException {
File f;
f = new File("input.csv");
if (!f.exists()) {
f.createNewFile();
System.out
.println("New file \"input.txt\" has been created to the current directory");
}
try {
- List<Integer> slas = new ArrayList<>();
+ List<Integer> slas = new ArrayList<Integer>();
BufferedWriter out = new BufferedWriter(new FileWriter("input.csv"));
RandomData randomData = new RandomDataImpl();
for(int k =0;k<11;k++){
// Runtime
int value = randomData.nextInt(1, 100);
out.write(value + ";");
// Slas
for (int i = 0; i < 3; i++){
int generatedValue= randomData.nextInt(10, 60);
slas.add(generatedValue);
out.write(generatedValue + ";");
}
// Cpu
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(0)), 5)).intValue()+ ";");
// Memory
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(1)), 5)).intValue()+ ";");
// Storage
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(2)), 5)).intValue()+ ";");
out.newLine();
out.flush();
}
} catch (IOException e) {
System.out.println("Excption while writing");
}
// RequestGenerator rg = RequestGenerator.getInstance();
// List<Request> requests = new ArrayList<Request>();
// requests = rg.generateRequests();
// for (Request r: requests){
// System.out.println(r.toString());
// System.out.println("");
// }
}
}
| true | true | public static void main(String args[]) throws IOException {
File f;
f = new File("input.csv");
if (!f.exists()) {
f.createNewFile();
System.out
.println("New file \"input.txt\" has been created to the current directory");
}
try {
List<Integer> slas = new ArrayList<>();
BufferedWriter out = new BufferedWriter(new FileWriter("input.csv"));
RandomData randomData = new RandomDataImpl();
for(int k =0;k<11;k++){
// Runtime
int value = randomData.nextInt(1, 100);
out.write(value + ";");
// Slas
for (int i = 0; i < 3; i++){
int generatedValue= randomData.nextInt(10, 60);
slas.add(generatedValue);
out.write(generatedValue + ";");
}
// Cpu
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(0)), 5)).intValue()+ ";");
// Memory
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(1)), 5)).intValue()+ ";");
// Storage
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(2)), 5)).intValue()+ ";");
out.newLine();
out.flush();
}
} catch (IOException e) {
System.out.println("Excption while writing");
}
// RequestGenerator rg = RequestGenerator.getInstance();
// List<Request> requests = new ArrayList<Request>();
// requests = rg.generateRequests();
// for (Request r: requests){
// System.out.println(r.toString());
// System.out.println("");
// }
}
| public static void main(String args[]) throws IOException {
File f;
f = new File("input.csv");
if (!f.exists()) {
f.createNewFile();
System.out
.println("New file \"input.txt\" has been created to the current directory");
}
try {
List<Integer> slas = new ArrayList<Integer>();
BufferedWriter out = new BufferedWriter(new FileWriter("input.csv"));
RandomData randomData = new RandomDataImpl();
for(int k =0;k<11;k++){
// Runtime
int value = randomData.nextInt(1, 100);
out.write(value + ";");
// Slas
for (int i = 0; i < 3; i++){
int generatedValue= randomData.nextInt(10, 60);
slas.add(generatedValue);
out.write(generatedValue + ";");
}
// Cpu
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(0)), 5)).intValue()+ ";");
// Memory
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(1)), 5)).intValue()+ ";");
// Storage
for (int i = 0; i < value; i++)
out.write(new Double(randomData.nextGaussian(randomData.nextInt(10, slas.get(2)), 5)).intValue()+ ";");
out.newLine();
out.flush();
}
} catch (IOException e) {
System.out.println("Excption while writing");
}
// RequestGenerator rg = RequestGenerator.getInstance();
// List<Request> requests = new ArrayList<Request>();
// requests = rg.generateRequests();
// for (Request r: requests){
// System.out.println(r.toString());
// System.out.println("");
// }
}
|
diff --git a/src/main/java/br/com/expense/util/FileUtil.java b/src/main/java/br/com/expense/util/FileUtil.java
index 155cf24..99134e1 100644
--- a/src/main/java/br/com/expense/util/FileUtil.java
+++ b/src/main/java/br/com/expense/util/FileUtil.java
@@ -1,66 +1,68 @@
package br.com.expense.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class FileUtil {
public static String entryLocation() {
return System.getProperty("user.dir");
}
public static String loadFile(String path) {
System.out.println(">> Loading content from file: " + path);
StringBuilder content = new StringBuilder();
Scanner sc = null;
try {
sc = new Scanner(new FileInputStream(path), "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNext()) {
content.append(sc.nextLine() + "\r\n");
}
return content.toString();
}
public static String loadFile(File baseDir, String file) {
return loadFile(new File(baseDir, file).getPath());
}
public static String loadFiles(File baseDir, String... files) {
StringBuilder content = new StringBuilder();
for (String file : files) {
content.append(loadFile(new File(baseDir, file).getPath()));
}
return content.toString();
}
public static void writeFile(File file, String content, String encoding) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
bw.write(content);
bw.flush();
bw.close();
} catch (IOException e) {
if (bw != null) {
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
+ } else {
+ e.printStackTrace();
}
}
}
public static void writeFile(File file, String content) {
writeFile(file, content, "UTF-8");
}
}
| true | true | public static void writeFile(File file, String content, String encoding) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
bw.write(content);
bw.flush();
bw.close();
} catch (IOException e) {
if (bw != null) {
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
| public static void writeFile(File file, String content, String encoding) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
bw.write(content);
bw.flush();
bw.close();
} catch (IOException e) {
if (bw != null) {
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
e.printStackTrace();
}
}
}
|
diff --git a/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java b/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
index b46390f..1d92a80 100644
--- a/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
+++ b/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
@@ -1,97 +1,97 @@
package org.elsys.homework_23;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
System.in.read();
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
- index--;
- info--;
+ index--;
+ info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
| true | true | public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
System.in.read();
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
| public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
System.in.read();
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
|
diff --git a/applications/petascope/src/main/java/petascope/wcs2/extensions/ExtensionsRegistry.java b/applications/petascope/src/main/java/petascope/wcs2/extensions/ExtensionsRegistry.java
index 23f547cb..799272ea 100644
--- a/applications/petascope/src/main/java/petascope/wcs2/extensions/ExtensionsRegistry.java
+++ b/applications/petascope/src/main/java/petascope/wcs2/extensions/ExtensionsRegistry.java
@@ -1,136 +1,135 @@
/*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <[email protected]>.
*/
package petascope.wcs2.extensions;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import petascope.HTTPRequest;
import petascope.wcs2.parsers.GetCoverageRequest;
/**
* Protocol binding extensions are managed in this class.
*
* @author <a href="mailto:[email protected]">Dimitar Misev</a>
*/
public class ExtensionsRegistry {
private static final Logger log = LoggerFactory.getLogger(ExtensionsRegistry.class);
public static final String XML_IDENTIFIER = "http://www.opengis.net/spec/WCS_protocol-binding_post-xml/1.0";
public static final String KVP_IDENTIFIER = "http://www.opengis.net/spec/WCS_protocol-binding_get-kvp/1.0/conf/get-kvp";
//@todo add a real url here
public static final String REST_IDENTIFIER = "http://www.opengis.net/spec/WCS_protocol-binding_get-rest/1.0/conf/get-rest";
public static final String SOAP_IDENTIFIER = "http://www.opengis.net/spec/WCS_protocol-binding_soap/1.0";
public static final String ENCODING_IDENTIFIER = "http://www.opengis.net/spec/GMLCOV/1.0/conf/gml-coverage";
public static final String GEOTIFF_IDENTIFIER = "http://www.opengis.net/spec/WCS_coverage-encoding_geotiff/1.0/";
public static final String JPEG2000_IDENTIFIER = "http://www.opengis.net/spec/WCS_coverage-encoding_jpeg2000/1.0/";
public static final String NETCDF_IDENTIFIER = "http://www.opengis.net/spec/WCS_coverage-encoding_netcdf/1.0/";
public static final String CRS_IDENTIFIER = "http://www.opengis.net/spec/WCS_service-extension_crs/1.0/conf/crs";
public static final String RANGE_SUBSETTING_IDENTIFIER = "http://www.opengis.net/spec/WCS_service-extension_range-subsetting/1.0/conf/";
public static final String SCALING_IDENTIFIER = "http://www.opengis.net/spec/WCS_service-extension_scaling/1.0/conf/scaling";
//public static final String CRS_DISCRETE_COVERAGE_IDENTIFIER = "http://www.opengis.net/spec/WCS_service-extension_crs/1.0/conf/crs-discrete-coverage";
//public static final String CRS_GRIDDED_COVERAGE_IDENTIFIER = "http://www.opengis.net/spec/WCS_service-extension_crs/1.0/conf/crs-grid-coverage";
private static final Set<Extension> extensions = new HashSet<Extension>();
private static final Set<String> extensionIds = new HashSet<String>();
static {
initialize();
}
/**
* Initialize registry: load available protocol binding extensions
*/
public static void initialize() {
registerExtension(new XMLProtocolExtension());
registerExtension(new SOAPProtocolExtension());
registerExtension(new KVPProtocolExtension());
registerExtension(new RESTProtocolExtension());
registerExtension(new GmlFormatExtension());
registerExtension(new GeotiffFormatExtension());
registerExtension(new JPEG2000FormatExtension());
registerExtension(new NetcdfFormatExtension());
registerExtension(new MultipartGeotiffFormatExtension());
registerExtension(new MultipartJPEG2000FormatExtension());
registerExtension(new MultipartNetcdfFormatExtension());
- registerExtension(new CRSExtension());
registerExtension(new RangeSubsettingExtension());
// registerExtension(new ScalingExtension());//only available at r'e
// Add crs.discrete.coverage and crs.gridded.coverage extensions ?
}
/**
* Add new extension to the registry. It will replace any other extension which has the same extension identifier.
*/
public static void registerExtension(Extension extension) {
log.info("Registered extension {}", extension);
extensions.add(extension);
extensionIds.add(extension.getExtensionIdentifier());
}
/**
* @return a binding for the specified operation, that can parse the specified input, or null otherwise
*/
public static ProtocolExtension getProtocolExtension(HTTPRequest request) {
for (Extension extension : extensions) {
if (extension instanceof ProtocolExtension && ((ProtocolExtension) extension).canHandle(request)) {
return (ProtocolExtension) extension;
}
}
return null;
}
public static FormatExtension getFormatExtension(GetCoverageRequest request) {
for (Extension extension : extensions) {
if (extension instanceof FormatExtension && ((FormatExtension) extension).canHandle(request)) {
return (FormatExtension) extension;
}
}
return null;
}
public static FormatExtension getFormatExtension(boolean multipart, String format) {
return getFormatExtension(new GetCoverageRequest(null, format, multipart));
}
public static Extension getExtension(String extensionIdentifier) {
for (Extension extension : extensions) {
if (extension.getExtensionIdentifier().equals(extensionIdentifier)) {
return extension;
}
}
return null;
}
/**
* @return the identifiers of all registered protocol binding extensions
*/
public static String[] getExtensionIds() {
return extensionIds.toArray(new String[extensionIds.size()]);
}
public static Set<Extension> getExtensions() {
return extensions;
}
}
| true | true | public static void initialize() {
registerExtension(new XMLProtocolExtension());
registerExtension(new SOAPProtocolExtension());
registerExtension(new KVPProtocolExtension());
registerExtension(new RESTProtocolExtension());
registerExtension(new GmlFormatExtension());
registerExtension(new GeotiffFormatExtension());
registerExtension(new JPEG2000FormatExtension());
registerExtension(new NetcdfFormatExtension());
registerExtension(new MultipartGeotiffFormatExtension());
registerExtension(new MultipartJPEG2000FormatExtension());
registerExtension(new MultipartNetcdfFormatExtension());
registerExtension(new CRSExtension());
registerExtension(new RangeSubsettingExtension());
// registerExtension(new ScalingExtension());//only available at r'e
// Add crs.discrete.coverage and crs.gridded.coverage extensions ?
}
| public static void initialize() {
registerExtension(new XMLProtocolExtension());
registerExtension(new SOAPProtocolExtension());
registerExtension(new KVPProtocolExtension());
registerExtension(new RESTProtocolExtension());
registerExtension(new GmlFormatExtension());
registerExtension(new GeotiffFormatExtension());
registerExtension(new JPEG2000FormatExtension());
registerExtension(new NetcdfFormatExtension());
registerExtension(new MultipartGeotiffFormatExtension());
registerExtension(new MultipartJPEG2000FormatExtension());
registerExtension(new MultipartNetcdfFormatExtension());
registerExtension(new RangeSubsettingExtension());
// registerExtension(new ScalingExtension());//only available at r'e
// Add crs.discrete.coverage and crs.gridded.coverage extensions ?
}
|
diff --git a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
index 37b74851..916f210a 100644
--- a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
+++ b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
@@ -1,353 +1,353 @@
/**
* Copyright 2008 Marvin Herman Froeder
* 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.sonatype.flexmojos.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.DirectoryScanner;
import org.sonatype.flexmojos.utilities.MavenUtils;
/**
* Goal to compile the Flex test sources.
*
* @author Marvin Herman Froeder ([email protected])
* @since 1.0
* @goal test-compile
* @requiresDependencyResolution
* @phase test
*/
public class TestCompilerMojo
extends ApplicationMojo
{
/**
* Set this to 'true' to bypass unit tests entirely. Its use is NOT RECOMMENDED, but quite convenient on occasion.
*
* @parameter expression="${maven.test.skip}"
*/
private boolean skipTests;
/**
* @parameter
*/
private File testRunnerTemplate;
/**
* File to be tested. If not defined assumes Test*.as and *Test.as
*
* @parameter
*/
private String[] includeTestFiles;
/**
* Files to exclude from testing. If not defined, assumes no exclusions
*
* @parameter
*/
private String[] excludeTestFiles;
/**
* @parameter expression="${project.build.testSourceDirectory}"
* @readonly
*/
private File testFolder;
/**
* Socket connect port for flex/java communication to transfer tests results
*
* @parameter default-value="13539" expression="${testPort}"
*/
private int testPort;
/**
* Socket connect port for flex/java communication to control if flashplayer is alive
*
* @parameter default-value="13540" expression="${testControlPort}"
*/
private int testControlPort;
@Override
public void execute()
throws MojoExecutionException, MojoFailureException
{
getLog().info(
"flexmojos " + MavenUtils.getFlexMojosVersion()
+ " - GNU GPL License (NO WARRANTY) - See COPYRIGHT file" );
if ( skipTests )
{
getLog().warn( "Skipping test phase." );
return;
}
else if ( !testFolder.exists() )
{
getLog().warn( "Test folder not found" + testFolder );
return;
}
setUp();
run();
tearDown();
}
@Override
public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
- if ( pattern.endsWith( ".java" ) )
+ if ( pattern.endsWith( ".as" ) )
{
- pattern = pattern.substring( 0, pattern.length() - 5 );
+ pattern = pattern.substring( 0, pattern.length() - 3 );
}
// Allow paths delimited by '.' or '/'
pattern = pattern.replace( '.', '/' );
includeTestFiles[i] = "**/" + pattern + ".as";
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
private List<String> getTestClasses()
{
getLog().debug(
"Scanning for tests at " + testFolder + " for " + Arrays.toString( includeTestFiles ) + " but "
+ Arrays.toString( excludeTestFiles ) );
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes( includeTestFiles );
scanner.setExcludes( excludeTestFiles );
scanner.addDefaultExcludes();
scanner.setBasedir( testFolder );
scanner.scan();
getLog().debug( "Test files: " + scanner.getIncludedFiles() );
List<String> testClasses = new ArrayList<String>();
for ( String testClass : scanner.getIncludedFiles() )
{
int endPoint = testClass.lastIndexOf( '.' );
testClass = testClass.substring( 0, endPoint ); // remove extension
testClass = testClass.replace( '/', '.' ); // Unix OS
testClass = testClass.replace( '\\', '.' ); // Windows OS
testClasses.add( testClass );
}
getLog().debug( "Test classes: " + testClasses );
return testClasses;
}
private File generateTester( List<String> testClasses )
throws Exception
{
// can't use velocity, got:
// java.io.InvalidClassException:
// org.apache.velocity.runtime.parser.node.ASTprocess; class invalid for
// deserialization
StringBuilder imports = new StringBuilder();
for ( String testClass : testClasses )
{
imports.append( "import " );
imports.append( testClass );
imports.append( ";" );
imports.append( '\n' );
}
StringBuilder classes = new StringBuilder();
for ( String testClass : testClasses )
{
testClass = testClass.substring( testClass.lastIndexOf( '.' ) + 1 );
classes.append( "addTest( " );
classes.append( testClass );
classes.append( ");" );
classes.append( '\n' );
}
InputStream templateSource = getTemplate();
String sourceString = IOUtils.toString( templateSource );
sourceString = sourceString.replace( "$imports", imports );
sourceString = sourceString.replace( "$testClasses", classes );
sourceString = sourceString.replace( "$port", String.valueOf( testPort ) );
sourceString = sourceString.replace( "$controlPort", String.valueOf( testControlPort ) );
File testSourceFile = new File( build.getTestOutputDirectory(), "TestRunner.mxml" );
FileWriter fileWriter = new FileWriter( testSourceFile );
IOUtils.write( sourceString, fileWriter );
fileWriter.flush();
fileWriter.close();
return testSourceFile;
}
private InputStream getTemplate()
throws MojoExecutionException
{
if ( testRunnerTemplate == null )
{
return getClass().getResourceAsStream( "/templates/test/TestRunner.vm" );
}
else if ( !testRunnerTemplate.exists() )
{
throw new MojoExecutionException( "Template file not found: " + testRunnerTemplate );
}
else
{
try
{
return new FileInputStream( testRunnerTemplate );
}
catch ( FileNotFoundException e )
{
// Never should happen
throw new MojoExecutionException( "Error reading template file", e );
}
}
}
@Override
protected void configure()
throws MojoExecutionException, MojoFailureException
{
compiledLocales = getLocales();
runtimeLocales = null;
super.configure();
// test launcher is at testOutputDirectory
configuration.addSourcePath( new File[] { new File( build.getTestOutputDirectory() ) } );
configuration.addSourcePath( getValidSourceRoots( project.getTestCompileSourceRoots() ).toArray( new File[0] ) );
if ( getResource( compiledLocales[0] ) != null )
{
configuration.addSourcePath( new File[] { new File( resourceBundlePath ) } );
}
configuration.allowSourcePathOverlap( true );
configuration.enableDebugging( true, super.debugPassword );
}
private File getResource( String locale )
{
try
{
return MavenUtils.getLocaleResourcePath( resourceBundlePath, locale );
}
catch ( MojoExecutionException e )
{
return null;
}
}
@Override
protected void resolveDependencies()
throws MojoExecutionException, MojoFailureException
{
configuration.setExternalLibraryPath( getGlobalDependency() );
// Set all dependencies as merged
configuration.setLibraryPath( getDependenciesPath( "compile" ) );
configuration.addLibraryPath( getDependenciesPath( "merged" ) );
configuration.addLibraryPath( merge( getResourcesBundles( getDefaultLocale() ),
getResourcesBundles( runtimeLocales ),
getResourcesBundles( compiledLocales ) ) );
// and add test libraries
configuration.includeLibraries( merge( getDependenciesPath( "internal" ), getDependenciesPath( "test" ),
getDependenciesPath( "rsl" ), getDependenciesPath( "caching" ),
getDependenciesPath( "external" ) ) );
configuration.setTheme( getThemes() );
}
private String[] getLocales()
{
if ( runtimeLocales == null && compiledLocales == null )
{
return new String[] { getDefaultLocale() };
}
Set<String> locales = new LinkedHashSet<String>();
if ( runtimeLocales != null )
{
locales.addAll( Arrays.asList( runtimeLocales ) );
}
if ( compiledLocales != null )
{
locales.addAll( Arrays.asList( compiledLocales ) );
}
return locales.toArray( new String[0] );
}
private File[] merge( File[]... filesSets )
{
List<File> files = new ArrayList<File>();
for ( File[] fileSet : filesSets )
{
files.addAll( Arrays.asList( fileSet ) );
}
return files.toArray( new File[0] );
}
@Override
protected File getOutput()
{
return new File( build.getTestOutputDirectory(), "TestRunner.swf" );
}
@Override
protected void compileModules()
throws MojoFailureException, MojoExecutionException
{
// modules are ignored on unit tests
}
}
| false | true | public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
if ( pattern.endsWith( ".java" ) )
{
pattern = pattern.substring( 0, pattern.length() - 5 );
}
// Allow paths delimited by '.' or '/'
pattern = pattern.replace( '.', '/' );
includeTestFiles[i] = "**/" + pattern + ".as";
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
| public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
if ( pattern.endsWith( ".as" ) )
{
pattern = pattern.substring( 0, pattern.length() - 3 );
}
// Allow paths delimited by '.' or '/'
pattern = pattern.replace( '.', '/' );
includeTestFiles[i] = "**/" + pattern + ".as";
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
|
diff --git a/src/fitnesse/testsystems/slim/tables/OrderedQueryTable.java b/src/fitnesse/testsystems/slim/tables/OrderedQueryTable.java
index eca72f742..cb3241c1e 100644
--- a/src/fitnesse/testsystems/slim/tables/OrderedQueryTable.java
+++ b/src/fitnesse/testsystems/slim/tables/OrderedQueryTable.java
@@ -1,44 +1,45 @@
package fitnesse.testsystems.slim.tables;
import fitnesse.testsystems.slim.SlimTestContext;
import fitnesse.testsystems.slim.Table;
import fitnesse.testsystems.slim.results.SlimTestResult;
public class OrderedQueryTable extends QueryTable {
private int lastMatchedRow = -1;
public OrderedQueryTable(Table table, String tableId, SlimTestContext slimTestContext) {
super(table, tableId, slimTestContext);
}
@Override
protected void scanRowForMatch(int tableRow, QueryResults queryResults) {
int matchedRow = queryResults.findBestMatch(tableRow);
if (matchedRow == -1) {
replaceAllvariablesInRow(tableRow);
SlimTestResult testResult = SlimTestResult.fail(null, table.getCellContents(0, tableRow), "missing");
+ getTestContext().increment(testResult.getExecutionResult());
table.updateContent(0, tableRow, testResult);
} else {
int columns = table.getColumnCountInRow(tableRow);
markColumns(tableRow, matchedRow, columns, queryResults);
lastMatchedRow = matchedRow;
}
}
private void markColumns(int tableRow, int matchedRow, int columns, QueryResults queryResults) {
for (int col = 0; col < columns; col++) {
markField(tableRow, matchedRow, col, queryResults);
}
}
@Override
protected SlimTestResult markMatch(int tableRow, int matchedRow, int col, String message) {
SlimTestResult testResult;
if (col == 0 && matchedRow <= lastMatchedRow) {
testResult = SlimTestResult.fail(null, message, "out of order: row " + (matchedRow + 1));
} else {
testResult = SlimTestResult.pass(message);
}
return testResult;
}
}
| true | true | protected void scanRowForMatch(int tableRow, QueryResults queryResults) {
int matchedRow = queryResults.findBestMatch(tableRow);
if (matchedRow == -1) {
replaceAllvariablesInRow(tableRow);
SlimTestResult testResult = SlimTestResult.fail(null, table.getCellContents(0, tableRow), "missing");
table.updateContent(0, tableRow, testResult);
} else {
int columns = table.getColumnCountInRow(tableRow);
markColumns(tableRow, matchedRow, columns, queryResults);
lastMatchedRow = matchedRow;
}
}
| protected void scanRowForMatch(int tableRow, QueryResults queryResults) {
int matchedRow = queryResults.findBestMatch(tableRow);
if (matchedRow == -1) {
replaceAllvariablesInRow(tableRow);
SlimTestResult testResult = SlimTestResult.fail(null, table.getCellContents(0, tableRow), "missing");
getTestContext().increment(testResult.getExecutionResult());
table.updateContent(0, tableRow, testResult);
} else {
int columns = table.getColumnCountInRow(tableRow);
markColumns(tableRow, matchedRow, columns, queryResults);
lastMatchedRow = matchedRow;
}
}
|
diff --git a/modules/activiti-rest/src/test/java/org/activiti/rest/api/runtime/TaskVariablesCollectionResourceTest.java b/modules/activiti-rest/src/test/java/org/activiti/rest/api/runtime/TaskVariablesCollectionResourceTest.java
index 67708ce2b..b157a56a4 100644
--- a/modules/activiti-rest/src/test/java/org/activiti/rest/api/runtime/TaskVariablesCollectionResourceTest.java
+++ b/modules/activiti-rest/src/test/java/org/activiti/rest/api/runtime/TaskVariablesCollectionResourceTest.java
@@ -1,133 +1,133 @@
/* 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.activiti.rest.api.runtime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.activiti.rest.BaseRestTestCase;
import org.activiti.rest.api.RestUrls;
import org.codehaus.jackson.JsonNode;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
/**
* Test for all REST-operations related to Task variables.
*
* @author Frederik Heremans
*/
public class TaskVariablesCollectionResourceTest extends BaseRestTestCase {
/**
* Test getting all task variables.
* GET runtime/tasks/{taskId}/variables
*/
@Deployment
- public void testGetTaskvariables() throws Exception {
+ public void testGetTaskVariables() throws Exception {
Calendar cal = Calendar.getInstance();
// Start process with all types of variables
Map<String, Object> processVariables = new HashMap<String, Object>();
processVariables.put("stringProcVar", "This is a ProcVariable");
processVariables.put("intProcVar", 123);
processVariables.put("longProcVar", 1234L);
processVariables.put("shortProcVar", (short) 123);
processVariables.put("doubleProcVar", 99.99);
processVariables.put("booleanProcVar", Boolean.TRUE);
processVariables.put("dateProcVar", cal.getTime());
processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
processVariables.put("overlappingVariable", "process-value");
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables);
// Set local task variables, including one that has the same name as one that is defined in the parent scope (process instance)
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put("stringTaskVar", "This is a TaskVariable");
taskVariables.put("intTaskVar", 123);
taskVariables.put("longTaskVar", 1234L);
taskVariables.put("shortTaskVar", (short) 123);
taskVariables.put("doubleTaskVar", 99.99);
taskVariables.put("booleanTaskVar", Boolean.TRUE);
taskVariables.put("dateTaskVar", cal.getTime());
taskVariables.put("byteArrayTaskVar", "Some raw bytes".getBytes());
taskVariables.put("overlappingVariable", "task-value");
taskService.setVariablesLocal(task.getId(), taskVariables);
// Request all variables (no scope provides) which include global an local
ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
Representation response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
JsonNode responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(17, responseNode.size());
// Overlapping variable should contain task-value AND be defined as "local"
boolean foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
if(var.get("name") != null && "overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("task-value", var.get("value").asText());
assertEquals("local", var.get("scope").asText());
break;
}
}
assertTrue(foundOverlapping);
// Check local variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=local");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("local", var.get("scope").asText());
}
// Check global variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=global");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("global", var.get("scope").asText());
if("overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("process-value", var.get("value").asText());
}
}
assertTrue(foundOverlapping);
}
}
| true | true | public void testGetTaskvariables() throws Exception {
Calendar cal = Calendar.getInstance();
// Start process with all types of variables
Map<String, Object> processVariables = new HashMap<String, Object>();
processVariables.put("stringProcVar", "This is a ProcVariable");
processVariables.put("intProcVar", 123);
processVariables.put("longProcVar", 1234L);
processVariables.put("shortProcVar", (short) 123);
processVariables.put("doubleProcVar", 99.99);
processVariables.put("booleanProcVar", Boolean.TRUE);
processVariables.put("dateProcVar", cal.getTime());
processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
processVariables.put("overlappingVariable", "process-value");
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables);
// Set local task variables, including one that has the same name as one that is defined in the parent scope (process instance)
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put("stringTaskVar", "This is a TaskVariable");
taskVariables.put("intTaskVar", 123);
taskVariables.put("longTaskVar", 1234L);
taskVariables.put("shortTaskVar", (short) 123);
taskVariables.put("doubleTaskVar", 99.99);
taskVariables.put("booleanTaskVar", Boolean.TRUE);
taskVariables.put("dateTaskVar", cal.getTime());
taskVariables.put("byteArrayTaskVar", "Some raw bytes".getBytes());
taskVariables.put("overlappingVariable", "task-value");
taskService.setVariablesLocal(task.getId(), taskVariables);
// Request all variables (no scope provides) which include global an local
ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
Representation response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
JsonNode responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(17, responseNode.size());
// Overlapping variable should contain task-value AND be defined as "local"
boolean foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
if(var.get("name") != null && "overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("task-value", var.get("value").asText());
assertEquals("local", var.get("scope").asText());
break;
}
}
assertTrue(foundOverlapping);
// Check local variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=local");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("local", var.get("scope").asText());
}
// Check global variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=global");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("global", var.get("scope").asText());
if("overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("process-value", var.get("value").asText());
}
}
assertTrue(foundOverlapping);
}
| public void testGetTaskVariables() throws Exception {
Calendar cal = Calendar.getInstance();
// Start process with all types of variables
Map<String, Object> processVariables = new HashMap<String, Object>();
processVariables.put("stringProcVar", "This is a ProcVariable");
processVariables.put("intProcVar", 123);
processVariables.put("longProcVar", 1234L);
processVariables.put("shortProcVar", (short) 123);
processVariables.put("doubleProcVar", 99.99);
processVariables.put("booleanProcVar", Boolean.TRUE);
processVariables.put("dateProcVar", cal.getTime());
processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
processVariables.put("overlappingVariable", "process-value");
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables);
// Set local task variables, including one that has the same name as one that is defined in the parent scope (process instance)
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put("stringTaskVar", "This is a TaskVariable");
taskVariables.put("intTaskVar", 123);
taskVariables.put("longTaskVar", 1234L);
taskVariables.put("shortTaskVar", (short) 123);
taskVariables.put("doubleTaskVar", 99.99);
taskVariables.put("booleanTaskVar", Boolean.TRUE);
taskVariables.put("dateTaskVar", cal.getTime());
taskVariables.put("byteArrayTaskVar", "Some raw bytes".getBytes());
taskVariables.put("overlappingVariable", "task-value");
taskService.setVariablesLocal(task.getId(), taskVariables);
// Request all variables (no scope provides) which include global an local
ClientResource client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
Representation response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
JsonNode responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(17, responseNode.size());
// Overlapping variable should contain task-value AND be defined as "local"
boolean foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
if(var.get("name") != null && "overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("task-value", var.get("value").asText());
assertEquals("local", var.get("scope").asText());
break;
}
}
assertTrue(foundOverlapping);
// Check local variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=local");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("local", var.get("scope").asText());
}
// Check global variables filering
client = getAuthenticatedClient(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()) + "?scope=global");
response = client.get();
assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus());
responseNode = objectMapper.readTree(response.getStream());
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(9, responseNode.size());
foundOverlapping = false;
for(int i=0; i< responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
assertEquals("global", var.get("scope").asText());
if("overlappingVariable".equals(var.get("name").asText())) {
foundOverlapping = true;
assertEquals("process-value", var.get("value").asText());
}
}
assertTrue(foundOverlapping);
}
|
diff --git a/src/main/java/org/springframework/jdbc/roma/generator/EnumFieldRowMapperGenerator.java b/src/main/java/org/springframework/jdbc/roma/generator/EnumFieldRowMapperGenerator.java
index 00033d1..6ec1096 100644
--- a/src/main/java/org/springframework/jdbc/roma/generator/EnumFieldRowMapperGenerator.java
+++ b/src/main/java/org/springframework/jdbc/roma/generator/EnumFieldRowMapperGenerator.java
@@ -1,106 +1,106 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.roma.generator;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.roma.config.manager.ConfigManager;
import org.springframework.jdbc.roma.domain.model.config.RowMapperEnumFieldConfig;
public class EnumFieldRowMapperGenerator<T> extends AbstractRowMapperFieldGenerator<T> {
private Object[] enumConstants;
private RowMapperEnumFieldConfig rmefc;
private String[] constantsAndMapsArray;
private Map<String, String> constantsAndMaps = new HashMap<String, String>();
public EnumFieldRowMapperGenerator(Field field, ConfigManager configManager) {
super(field, configManager);
init();
}
private void init() {
enumConstants = fieldCls.getEnumConstants();
rmefc = configManager.getRowMapperEnumFieldConfig(field);
if (rmefc != null) {
constantsAndMapsArray = rmefc.getConstantsAndMaps();
if (constantsAndMapsArray != null) {
for (String constantAndMap : constantsAndMapsArray) {
String[] constantAndMapParts = constantAndMap.split(":");
String constant = constantAndMapParts[0];
String map = constantAndMapParts[1];
constantsAndMaps.put(constant, map);
}
}
}
}
@Override
public String doFieldMapping(Field f) {
String setterMethodName = getSetterMethodName(f);
if (enumConstants == null) {
return null;
}
String setValueExpr = RESULT_SET_ARGUMENT + ".getInt(\"" + columnName + "\")";
if (f.getType().equals(Integer.class)) {
setValueExpr = "Integer.valueOf" + "(" + setValueExpr + ")";
}
if (rmefc == null) {
- setValueExpr = f.getType() + ".values()" + "[" + setValueExpr + "]";
+ setValueExpr = f.getType().getName() + ".values()" + "[" + setValueExpr + "]";
return
wrapWithNullCheck(
GENERATED_OBJECT_NAME + "." + setterMethodName + "(" + setValueExpr + ");",
setterMethodName);
}
else {
StringBuffer sb = new StringBuffer();
String intValueFieldName = field.getName() + "IntVal";
sb.
append("Integer " + intValueFieldName).
append(" = ").
append("Integer.valueOf").append("(").append(setValueExpr).append(")").
append(";").append("\n");
for (int i = 0; i < constantsAndMapsArray.length; i++) {
String constantAndMap = constantsAndMapsArray[i];
String[] constantAndMapParts = constantAndMap.split(":");
String constant = constantAndMapParts[0];
String map = constantAndMapParts[1];
sb.append("\t");
if (i > 0) {
sb.append("else ");
}
sb.
append("if ").
append("(").
append(intValueFieldName + ".equals" + "(" + "Integer.valueOf" + "(" + constant + ")" + ")").
append(")").append("\n").
append("\t").append("{").append("\n").
append("\t").append("\t").append(GENERATED_OBJECT_NAME + "." + setterMethodName).
append("(").
append(fieldCls.getName() + ".valueOf" + "(" + "\"" + map + "\"" + ")").
append(")").append(";").append("\n").
append("\t").append("}").append("\n");
}
return wrapWithExceptionHandling(sb.toString());
}
}
}
| true | true | public String doFieldMapping(Field f) {
String setterMethodName = getSetterMethodName(f);
if (enumConstants == null) {
return null;
}
String setValueExpr = RESULT_SET_ARGUMENT + ".getInt(\"" + columnName + "\")";
if (f.getType().equals(Integer.class)) {
setValueExpr = "Integer.valueOf" + "(" + setValueExpr + ")";
}
if (rmefc == null) {
setValueExpr = f.getType() + ".values()" + "[" + setValueExpr + "]";
return
wrapWithNullCheck(
GENERATED_OBJECT_NAME + "." + setterMethodName + "(" + setValueExpr + ");",
setterMethodName);
}
else {
StringBuffer sb = new StringBuffer();
String intValueFieldName = field.getName() + "IntVal";
sb.
append("Integer " + intValueFieldName).
append(" = ").
append("Integer.valueOf").append("(").append(setValueExpr).append(")").
append(";").append("\n");
for (int i = 0; i < constantsAndMapsArray.length; i++) {
String constantAndMap = constantsAndMapsArray[i];
String[] constantAndMapParts = constantAndMap.split(":");
String constant = constantAndMapParts[0];
String map = constantAndMapParts[1];
sb.append("\t");
if (i > 0) {
sb.append("else ");
}
sb.
append("if ").
append("(").
append(intValueFieldName + ".equals" + "(" + "Integer.valueOf" + "(" + constant + ")" + ")").
append(")").append("\n").
append("\t").append("{").append("\n").
append("\t").append("\t").append(GENERATED_OBJECT_NAME + "." + setterMethodName).
append("(").
append(fieldCls.getName() + ".valueOf" + "(" + "\"" + map + "\"" + ")").
append(")").append(";").append("\n").
append("\t").append("}").append("\n");
}
return wrapWithExceptionHandling(sb.toString());
}
}
| public String doFieldMapping(Field f) {
String setterMethodName = getSetterMethodName(f);
if (enumConstants == null) {
return null;
}
String setValueExpr = RESULT_SET_ARGUMENT + ".getInt(\"" + columnName + "\")";
if (f.getType().equals(Integer.class)) {
setValueExpr = "Integer.valueOf" + "(" + setValueExpr + ")";
}
if (rmefc == null) {
setValueExpr = f.getType().getName() + ".values()" + "[" + setValueExpr + "]";
return
wrapWithNullCheck(
GENERATED_OBJECT_NAME + "." + setterMethodName + "(" + setValueExpr + ");",
setterMethodName);
}
else {
StringBuffer sb = new StringBuffer();
String intValueFieldName = field.getName() + "IntVal";
sb.
append("Integer " + intValueFieldName).
append(" = ").
append("Integer.valueOf").append("(").append(setValueExpr).append(")").
append(";").append("\n");
for (int i = 0; i < constantsAndMapsArray.length; i++) {
String constantAndMap = constantsAndMapsArray[i];
String[] constantAndMapParts = constantAndMap.split(":");
String constant = constantAndMapParts[0];
String map = constantAndMapParts[1];
sb.append("\t");
if (i > 0) {
sb.append("else ");
}
sb.
append("if ").
append("(").
append(intValueFieldName + ".equals" + "(" + "Integer.valueOf" + "(" + constant + ")" + ")").
append(")").append("\n").
append("\t").append("{").append("\n").
append("\t").append("\t").append(GENERATED_OBJECT_NAME + "." + setterMethodName).
append("(").
append(fieldCls.getName() + ".valueOf" + "(" + "\"" + map + "\"" + ")").
append(")").append(";").append("\n").
append("\t").append("}").append("\n");
}
return wrapWithExceptionHandling(sb.toString());
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/VMLibraryBlock.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/VMLibraryBlock.java
index 902c15ef8..1f4b2134a 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/VMLibraryBlock.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/VMLibraryBlock.java
@@ -1,411 +1,412 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.jres;
import java.io.File;
import java.net.URL;
import java.util.Iterator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.SWTFactory;
import org.eclipse.jdt.internal.debug.ui.jres.LibraryContentProvider.SubElement;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMInstallType;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.LibraryLocation;
import org.eclipse.jdt.ui.wizards.BuildPathDialogAccess;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
/**
* Control used to edit the libraries associated with a VM install
*/
public class VMLibraryBlock implements SelectionListener, ISelectionChangedListener {
/**
* Attribute name for the last path used to open a file/directory chooser
* dialog.
*/
protected static final String LAST_PATH_SETTING = "LAST_PATH_SETTING"; //$NON-NLS-1$
/**
* the prefix for dialog setting pertaining to this block
*/
protected static final String DIALOG_SETTINGS_PREFIX = "VMLibraryBlock"; //$NON-NLS-1$
protected boolean fInCallback = false;
protected IVMInstall fVmInstall;
protected IVMInstallType fVmInstallType;
protected File fHome;
//widgets
protected LibraryContentProvider fLibraryContentProvider;
protected AddVMDialog fDialog = null;
protected TreeViewer fLibraryViewer;
private Button fUpButton;
private Button fDownButton;
private Button fRemoveButton;
private Button fAddButton;
private Button fJavadocButton;
private Button fSourceButton;
protected Button fDefaultButton;
/**
* Constructor for VMLibraryBlock.
*/
public VMLibraryBlock(AddVMDialog dialog) {
fDialog = dialog;
}
/**
* Creates and returns the source lookup control.
*
* @param parent the parent widget of this control
*/
public Control createControl(Composite parent) {
Font font = parent.getFont();
Composite comp = SWTFactory.createComposite(parent, font, 2, 1, GridData.FILL_BOTH, 0, 0);
fLibraryViewer= new TreeViewer(comp);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 6;
fLibraryViewer.getControl().setLayoutData(gd);
fLibraryContentProvider= new LibraryContentProvider();
fLibraryViewer.setContentProvider(fLibraryContentProvider);
fLibraryViewer.setLabelProvider(new LibraryLabelProvider());
fLibraryViewer.setInput(this);
fLibraryViewer.addSelectionChangedListener(this);
Composite pathButtonComp = SWTFactory.createComposite(comp, font, 1, 1, GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL, 0, 0);
fAddButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_7, JREMessages.VMLibraryBlock_16, null);
fAddButton.addSelectionListener(this);
fJavadocButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_3, JREMessages.VMLibraryBlock_17, null);
fJavadocButton.addSelectionListener(this);
fSourceButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_11, JREMessages.VMLibraryBlock_18, null);
fSourceButton.addSelectionListener(this);
fLibraryViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
IStructuredSelection sel = (IStructuredSelection)event.getViewer().getSelection();
Object obj = sel.getFirstElement();
if(obj instanceof SubElement) {
edit(sel, ((SubElement)obj).getType());
}
}
});
fRemoveButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_6, JREMessages.VMLibraryBlock_12, null);
fRemoveButton.addSelectionListener(this);
fUpButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_4, JREMessages.VMLibraryBlock_13, null);
fUpButton.addSelectionListener(this);
fDownButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_5, JREMessages.VMLibraryBlock_14, null);
fDownButton.addSelectionListener(this);
fDefaultButton = SWTFactory.createPushButton(pathButtonComp, JREMessages.VMLibraryBlock_9, JREMessages.VMLibraryBlock_15, null);
fDefaultButton.addSelectionListener(this);
return comp;
}
/**
* The "default" button has been toggled
*/
public void restoreDefaultLibraries() {
LibraryLocation[] libs = null;
File installLocation = getHomeDirectory();
if (installLocation == null) {
libs = new LibraryLocation[0];
} else {
libs = getVMInstallType().getDefaultLibraryLocations(installLocation);
}
fLibraryContentProvider.setLibraries(libs);
update();
}
/**
* Initializes this control based on the settings in the given
* vm install and type.
*
* @param vm vm or <code>null</code> if none
* @param type type of vm install
*/
public void initializeFrom(IVMInstall vm, IVMInstallType type) {
fVmInstall = vm;
fVmInstallType = type;
if (vm != null) {
setHomeDirectory(vm.getInstallLocation());
fLibraryContentProvider.setLibraries(JavaRuntime.getLibraryLocations(getVMInstall()));
}
update();
}
/**
* Sets the home directory of the VM Install the user has chosen
*/
public void setHomeDirectory(File file) {
fHome = file;
}
/**
* Returns the home directory
*/
protected File getHomeDirectory() {
return fHome;
}
/**
* Updates buttons and status based on current libraries
*/
public void update() {
updateButtons();
IStatus status = Status.OK_STATUS;
if (fLibraryContentProvider.getLibraries().length == 0) { // && !isDefaultSystemLibrary()) {
status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR, "Libraries cannot be empty.", null); //$NON-NLS-1$
}
LibraryStandin[] standins = fLibraryContentProvider.getStandins();
for (int i = 0; i < standins.length; i++) {
IStatus st = standins[i].validate();
if (!st.isOK()) {
status = st;
break;
}
}
fDialog.setSystemLibraryStatus(status);
fDialog.updateStatusLine();
}
/**
* Saves settings in the given working copy
*/
- public void performApply(IVMInstall vm) {
- if (isDefaultLocations()) {
+ public void performApply(IVMInstall vm) {
+ if (isDefaultLocations(vm)) {
vm.setLibraryLocations(null);
} else {
LibraryLocation[] libs = fLibraryContentProvider.getLibraries();
vm.setLibraryLocations(libs);
}
}
/**
- * Determines if the present setup is the default location s for this JRE
+ * Determines if the current libraries displayed to the user are the default location
+ * for the given vm working copy.
+ * @param vm the virtual machine to check for the default location
* @return true if the current set of locations are the defaults, false otherwise
*/
- protected boolean isDefaultLocations() {
+ protected boolean isDefaultLocations(IVMInstall vm) {
LibraryLocation[] libraryLocations = fLibraryContentProvider.getLibraries();
- IVMInstall install = getVMInstall();
- if (install == null || libraryLocations == null) {
+ if (vm == null || libraryLocations == null) {
return true;
}
- File installLocation = install.getInstallLocation();
+ File installLocation = vm.getInstallLocation();
if (installLocation != null) {
LibraryLocation[] def = getVMInstallType().getDefaultLibraryLocations(installLocation);
if (def.length == libraryLocations.length) {
for (int i = 0; i < def.length; i++) {
if (!def[i].equals(libraryLocations[i])) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Returns the vm install associated with this library block.
*
* @return vm install
*/
protected IVMInstall getVMInstall() {
return fVmInstall;
}
/**
* Returns the vm install type associated with this library block.
*
* @return vm install
*/
protected IVMInstallType getVMInstallType() {
return fVmInstallType;
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
Object source= e.getSource();
if (source == fUpButton) {
fLibraryContentProvider.up((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fDownButton) {
fLibraryContentProvider.down((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fRemoveButton) {
fLibraryContentProvider.remove((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fAddButton) {
add((IStructuredSelection) fLibraryViewer.getSelection());
}
else if(source == fJavadocButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.JAVADOC_URL);
}
else if(source == fSourceButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.SOURCE_PATH);
}
else if (source == fDefaultButton) {
restoreDefaultLibraries();
}
update();
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent e) {}
/**
* Open the file selection dialog, and add the return jars as libraries.
*/
private void add(IStructuredSelection selection) {
IDialogSettings dialogSettings= JDIDebugUIPlugin.getDefault().getDialogSettings();
String lastUsedPath= dialogSettings.get(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
FileDialog dialog= new FileDialog(fLibraryViewer.getControl().getShell(), SWT.MULTI);
dialog.setText(JREMessages.VMLibraryBlock_10);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
LibraryLocation[] libs= new LibraryLocation[nChosen];
for (int i= 0; i < nChosen; i++) {
libs[i]= new LibraryLocation(filterPath.append(fileNames[i]).makeAbsolute(), Path.EMPTY, Path.EMPTY);
}
dialogSettings.put(LAST_PATH_SETTING, filterPath.toOSString());
fLibraryContentProvider.add(libs, selection);
}
/**
* Open the javadoc location dialog or the source location dialog, and set the result
* to the selected libraries.
*/
private void edit(IStructuredSelection selection, int type) {
Object obj = selection.getFirstElement();
LibraryStandin standin = null;
if(obj instanceof LibraryStandin) {
standin = (LibraryStandin) obj;
}
else if(obj instanceof SubElement){
SubElement sub = (SubElement)obj;
standin = sub.getParent();
}
if(standin != null) {
LibraryLocation library = standin.toLibraryLocation();
if (type == SubElement.JAVADOC_URL) {
URL[] urls = BuildPathDialogAccess.configureJavadocLocation(fLibraryViewer.getControl().getShell(), library.getSystemLibraryPath().toOSString(), library.getJavadocLocation());
if (urls != null) {
fLibraryContentProvider.setJavadoc(urls[0], selection);
}
}
else if(type == SubElement.SOURCE_PATH){
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(library.getSystemLibraryPath());
entry.setSourceAttachmentPath(library.getSystemLibrarySourcePath());
entry.setSourceAttachmentRootPath(library.getPackageRootPath());
IClasspathEntry classpathEntry = BuildPathDialogAccess.configureSourceAttachment(fLibraryViewer.getControl().getShell(), entry.getClasspathEntry());
if (classpathEntry != null) {
fLibraryContentProvider.setSourcePath(classpathEntry.getSourceAttachmentPath(), classpathEntry.getSourceAttachmentRootPath(), selection);
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
updateButtons();
}
/**
* Refresh the enable/disable state for the buttons.
*/
private void updateButtons() {
IStructuredSelection selection = (IStructuredSelection) fLibraryViewer.getSelection();
fRemoveButton.setEnabled(!selection.isEmpty());
boolean enableUp = true,
enableDown = true,
allSource = true,
allJavadoc = true,
allRoots = true;
Object[] libraries = fLibraryContentProvider.getElements(null);
if (selection.isEmpty() || libraries.length == 0) {
enableUp = false;
enableDown = false;
} else {
Object first = libraries[0];
Object last = libraries[libraries.length - 1];
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= iter.next();
Object lib;
if (element instanceof SubElement) {
allRoots = false;
SubElement subElement= (SubElement)element;
lib = (subElement).getParent().toLibraryLocation();
if (subElement.getType() == SubElement.JAVADOC_URL) {
allSource = false;
} else {
allJavadoc = false;
}
} else {
lib = element;
allSource = false;
allJavadoc = false;
}
if (lib == first) {
enableUp = false;
}
if (lib == last) {
enableDown = false;
}
}
}
fUpButton.setEnabled(enableUp);
fDownButton.setEnabled(enableDown);
fJavadocButton.setEnabled(!selection.isEmpty() && (allJavadoc || allRoots));
fSourceButton.setEnabled(!selection.isEmpty() && (allSource || allRoots));
}
}
| false | true | public void update() {
updateButtons();
IStatus status = Status.OK_STATUS;
if (fLibraryContentProvider.getLibraries().length == 0) { // && !isDefaultSystemLibrary()) {
status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR, "Libraries cannot be empty.", null); //$NON-NLS-1$
}
LibraryStandin[] standins = fLibraryContentProvider.getStandins();
for (int i = 0; i < standins.length; i++) {
IStatus st = standins[i].validate();
if (!st.isOK()) {
status = st;
break;
}
}
fDialog.setSystemLibraryStatus(status);
fDialog.updateStatusLine();
}
/**
* Saves settings in the given working copy
*/
public void performApply(IVMInstall vm) {
if (isDefaultLocations()) {
vm.setLibraryLocations(null);
} else {
LibraryLocation[] libs = fLibraryContentProvider.getLibraries();
vm.setLibraryLocations(libs);
}
}
/**
* Determines if the present setup is the default location s for this JRE
* @return true if the current set of locations are the defaults, false otherwise
*/
protected boolean isDefaultLocations() {
LibraryLocation[] libraryLocations = fLibraryContentProvider.getLibraries();
IVMInstall install = getVMInstall();
if (install == null || libraryLocations == null) {
return true;
}
File installLocation = install.getInstallLocation();
if (installLocation != null) {
LibraryLocation[] def = getVMInstallType().getDefaultLibraryLocations(installLocation);
if (def.length == libraryLocations.length) {
for (int i = 0; i < def.length; i++) {
if (!def[i].equals(libraryLocations[i])) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Returns the vm install associated with this library block.
*
* @return vm install
*/
protected IVMInstall getVMInstall() {
return fVmInstall;
}
/**
* Returns the vm install type associated with this library block.
*
* @return vm install
*/
protected IVMInstallType getVMInstallType() {
return fVmInstallType;
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
Object source= e.getSource();
if (source == fUpButton) {
fLibraryContentProvider.up((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fDownButton) {
fLibraryContentProvider.down((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fRemoveButton) {
fLibraryContentProvider.remove((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fAddButton) {
add((IStructuredSelection) fLibraryViewer.getSelection());
}
else if(source == fJavadocButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.JAVADOC_URL);
}
else if(source == fSourceButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.SOURCE_PATH);
}
else if (source == fDefaultButton) {
restoreDefaultLibraries();
}
update();
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent e) {}
/**
* Open the file selection dialog, and add the return jars as libraries.
*/
private void add(IStructuredSelection selection) {
IDialogSettings dialogSettings= JDIDebugUIPlugin.getDefault().getDialogSettings();
String lastUsedPath= dialogSettings.get(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
FileDialog dialog= new FileDialog(fLibraryViewer.getControl().getShell(), SWT.MULTI);
dialog.setText(JREMessages.VMLibraryBlock_10);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
LibraryLocation[] libs= new LibraryLocation[nChosen];
for (int i= 0; i < nChosen; i++) {
libs[i]= new LibraryLocation(filterPath.append(fileNames[i]).makeAbsolute(), Path.EMPTY, Path.EMPTY);
}
dialogSettings.put(LAST_PATH_SETTING, filterPath.toOSString());
fLibraryContentProvider.add(libs, selection);
}
/**
* Open the javadoc location dialog or the source location dialog, and set the result
* to the selected libraries.
*/
private void edit(IStructuredSelection selection, int type) {
Object obj = selection.getFirstElement();
LibraryStandin standin = null;
if(obj instanceof LibraryStandin) {
standin = (LibraryStandin) obj;
}
else if(obj instanceof SubElement){
SubElement sub = (SubElement)obj;
standin = sub.getParent();
}
if(standin != null) {
LibraryLocation library = standin.toLibraryLocation();
if (type == SubElement.JAVADOC_URL) {
URL[] urls = BuildPathDialogAccess.configureJavadocLocation(fLibraryViewer.getControl().getShell(), library.getSystemLibraryPath().toOSString(), library.getJavadocLocation());
if (urls != null) {
fLibraryContentProvider.setJavadoc(urls[0], selection);
}
}
else if(type == SubElement.SOURCE_PATH){
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(library.getSystemLibraryPath());
entry.setSourceAttachmentPath(library.getSystemLibrarySourcePath());
entry.setSourceAttachmentRootPath(library.getPackageRootPath());
IClasspathEntry classpathEntry = BuildPathDialogAccess.configureSourceAttachment(fLibraryViewer.getControl().getShell(), entry.getClasspathEntry());
if (classpathEntry != null) {
fLibraryContentProvider.setSourcePath(classpathEntry.getSourceAttachmentPath(), classpathEntry.getSourceAttachmentRootPath(), selection);
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
updateButtons();
}
/**
* Refresh the enable/disable state for the buttons.
*/
private void updateButtons() {
IStructuredSelection selection = (IStructuredSelection) fLibraryViewer.getSelection();
fRemoveButton.setEnabled(!selection.isEmpty());
boolean enableUp = true,
enableDown = true,
allSource = true,
allJavadoc = true,
allRoots = true;
Object[] libraries = fLibraryContentProvider.getElements(null);
if (selection.isEmpty() || libraries.length == 0) {
enableUp = false;
enableDown = false;
} else {
Object first = libraries[0];
Object last = libraries[libraries.length - 1];
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= iter.next();
Object lib;
if (element instanceof SubElement) {
allRoots = false;
SubElement subElement= (SubElement)element;
lib = (subElement).getParent().toLibraryLocation();
if (subElement.getType() == SubElement.JAVADOC_URL) {
allSource = false;
} else {
allJavadoc = false;
}
} else {
lib = element;
allSource = false;
allJavadoc = false;
}
if (lib == first) {
enableUp = false;
}
if (lib == last) {
enableDown = false;
}
}
}
fUpButton.setEnabled(enableUp);
fDownButton.setEnabled(enableDown);
fJavadocButton.setEnabled(!selection.isEmpty() && (allJavadoc || allRoots));
fSourceButton.setEnabled(!selection.isEmpty() && (allSource || allRoots));
}
}
| public void update() {
updateButtons();
IStatus status = Status.OK_STATUS;
if (fLibraryContentProvider.getLibraries().length == 0) { // && !isDefaultSystemLibrary()) {
status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR, "Libraries cannot be empty.", null); //$NON-NLS-1$
}
LibraryStandin[] standins = fLibraryContentProvider.getStandins();
for (int i = 0; i < standins.length; i++) {
IStatus st = standins[i].validate();
if (!st.isOK()) {
status = st;
break;
}
}
fDialog.setSystemLibraryStatus(status);
fDialog.updateStatusLine();
}
/**
* Saves settings in the given working copy
*/
public void performApply(IVMInstall vm) {
if (isDefaultLocations(vm)) {
vm.setLibraryLocations(null);
} else {
LibraryLocation[] libs = fLibraryContentProvider.getLibraries();
vm.setLibraryLocations(libs);
}
}
/**
* Determines if the current libraries displayed to the user are the default location
* for the given vm working copy.
* @param vm the virtual machine to check for the default location
* @return true if the current set of locations are the defaults, false otherwise
*/
protected boolean isDefaultLocations(IVMInstall vm) {
LibraryLocation[] libraryLocations = fLibraryContentProvider.getLibraries();
if (vm == null || libraryLocations == null) {
return true;
}
File installLocation = vm.getInstallLocation();
if (installLocation != null) {
LibraryLocation[] def = getVMInstallType().getDefaultLibraryLocations(installLocation);
if (def.length == libraryLocations.length) {
for (int i = 0; i < def.length; i++) {
if (!def[i].equals(libraryLocations[i])) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Returns the vm install associated with this library block.
*
* @return vm install
*/
protected IVMInstall getVMInstall() {
return fVmInstall;
}
/**
* Returns the vm install type associated with this library block.
*
* @return vm install
*/
protected IVMInstallType getVMInstallType() {
return fVmInstallType;
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent e) {
Object source= e.getSource();
if (source == fUpButton) {
fLibraryContentProvider.up((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fDownButton) {
fLibraryContentProvider.down((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fRemoveButton) {
fLibraryContentProvider.remove((IStructuredSelection) fLibraryViewer.getSelection());
} else if (source == fAddButton) {
add((IStructuredSelection) fLibraryViewer.getSelection());
}
else if(source == fJavadocButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.JAVADOC_URL);
}
else if(source == fSourceButton) {
edit((IStructuredSelection) fLibraryViewer.getSelection(), SubElement.SOURCE_PATH);
}
else if (source == fDefaultButton) {
restoreDefaultLibraries();
}
update();
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent e) {}
/**
* Open the file selection dialog, and add the return jars as libraries.
*/
private void add(IStructuredSelection selection) {
IDialogSettings dialogSettings= JDIDebugUIPlugin.getDefault().getDialogSettings();
String lastUsedPath= dialogSettings.get(LAST_PATH_SETTING);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
FileDialog dialog= new FileDialog(fLibraryViewer.getControl().getShell(), SWT.MULTI);
dialog.setText(JREMessages.VMLibraryBlock_10);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
String res= dialog.open();
if (res == null) {
return;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
LibraryLocation[] libs= new LibraryLocation[nChosen];
for (int i= 0; i < nChosen; i++) {
libs[i]= new LibraryLocation(filterPath.append(fileNames[i]).makeAbsolute(), Path.EMPTY, Path.EMPTY);
}
dialogSettings.put(LAST_PATH_SETTING, filterPath.toOSString());
fLibraryContentProvider.add(libs, selection);
}
/**
* Open the javadoc location dialog or the source location dialog, and set the result
* to the selected libraries.
*/
private void edit(IStructuredSelection selection, int type) {
Object obj = selection.getFirstElement();
LibraryStandin standin = null;
if(obj instanceof LibraryStandin) {
standin = (LibraryStandin) obj;
}
else if(obj instanceof SubElement){
SubElement sub = (SubElement)obj;
standin = sub.getParent();
}
if(standin != null) {
LibraryLocation library = standin.toLibraryLocation();
if (type == SubElement.JAVADOC_URL) {
URL[] urls = BuildPathDialogAccess.configureJavadocLocation(fLibraryViewer.getControl().getShell(), library.getSystemLibraryPath().toOSString(), library.getJavadocLocation());
if (urls != null) {
fLibraryContentProvider.setJavadoc(urls[0], selection);
}
}
else if(type == SubElement.SOURCE_PATH){
IRuntimeClasspathEntry entry = JavaRuntime.newArchiveRuntimeClasspathEntry(library.getSystemLibraryPath());
entry.setSourceAttachmentPath(library.getSystemLibrarySourcePath());
entry.setSourceAttachmentRootPath(library.getPackageRootPath());
IClasspathEntry classpathEntry = BuildPathDialogAccess.configureSourceAttachment(fLibraryViewer.getControl().getShell(), entry.getClasspathEntry());
if (classpathEntry != null) {
fLibraryContentProvider.setSourcePath(classpathEntry.getSourceAttachmentPath(), classpathEntry.getSourceAttachmentRootPath(), selection);
}
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
updateButtons();
}
/**
* Refresh the enable/disable state for the buttons.
*/
private void updateButtons() {
IStructuredSelection selection = (IStructuredSelection) fLibraryViewer.getSelection();
fRemoveButton.setEnabled(!selection.isEmpty());
boolean enableUp = true,
enableDown = true,
allSource = true,
allJavadoc = true,
allRoots = true;
Object[] libraries = fLibraryContentProvider.getElements(null);
if (selection.isEmpty() || libraries.length == 0) {
enableUp = false;
enableDown = false;
} else {
Object first = libraries[0];
Object last = libraries[libraries.length - 1];
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= iter.next();
Object lib;
if (element instanceof SubElement) {
allRoots = false;
SubElement subElement= (SubElement)element;
lib = (subElement).getParent().toLibraryLocation();
if (subElement.getType() == SubElement.JAVADOC_URL) {
allSource = false;
} else {
allJavadoc = false;
}
} else {
lib = element;
allSource = false;
allJavadoc = false;
}
if (lib == first) {
enableUp = false;
}
if (lib == last) {
enableDown = false;
}
}
}
fUpButton.setEnabled(enableUp);
fDownButton.setEnabled(enableDown);
fJavadocButton.setEnabled(!selection.isEmpty() && (allJavadoc || allRoots));
fSourceButton.setEnabled(!selection.isEmpty() && (allSource || allRoots));
}
}
|
diff --git a/src/main/java/nl/topicus/onderwijs/dashboard/modules/ns/NSService.java b/src/main/java/nl/topicus/onderwijs/dashboard/modules/ns/NSService.java
index 92a9f86..56770b5 100644
--- a/src/main/java/nl/topicus/onderwijs/dashboard/modules/ns/NSService.java
+++ b/src/main/java/nl/topicus/onderwijs/dashboard/modules/ns/NSService.java
@@ -1,165 +1,165 @@
package nl.topicus.onderwijs.dashboard.modules.ns;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import nl.topicus.onderwijs.dashboard.datasources.Trains;
import nl.topicus.onderwijs.dashboard.keys.Key;
import nl.topicus.onderwijs.dashboard.modules.Repository;
import nl.topicus.onderwijs.dashboard.modules.Settings;
import nl.topicus.onderwijs.dashboard.modules.ns.model.Train;
import nl.topicus.onderwijs.dashboard.modules.ns.model.TrainType;
import nl.topicus.onderwijs.dashboard.modules.topicus.Retriever;
import nl.topicus.onderwijs.dashboard.modules.topicus.RetrieverUtils;
import nl.topicus.onderwijs.dashboard.modules.topicus.StatusPageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NSService implements Retriever {
private static final Logger log = LoggerFactory.getLogger(NSService.class);
private static final int TIME = 0;
private static final int DESTINATION = 1;
private static final int PLATFORM = 2;
private static final int DETAILS = 4;
private Map<Key, List<Train>> trains = new HashMap<Key, List<Train>>();
@Override
public void onConfigure(Repository repository) {
for (Key key : Settings.get().getKeysWithConfigurationFor(
NSService.class)) {
trains.put(key, Collections.<Train> emptyList());
repository.addDataSource(key, Trains.class, new TrainsImpl(key,
this));
}
}
@Override
public void refreshData() {
Map<Key, List<Train>> newTrains = new HashMap<Key, List<Train>>();
Map<Key, Map<String, ?>> serviceSettings = Settings.get()
.getServiceSettings(NSService.class);
for (Map.Entry<Key, Map<String, ?>> configEntry : serviceSettings
.entrySet()) {
Key location = configEntry.getKey();
String station = configEntry.getValue().get("station").toString();
newTrains.put(location, fetchDepartures(location, station));
}
trains = newTrains;
}
private List<Train> fetchDepartures(Key location, String station) {
try {
// StatusPageResponse response = RetrieverUtils
// .getStatuspage("http://192.168.55.113/api/json");
StatusPageResponse response = RetrieverUtils
- .getStatuspage("http://www.ns.nl/actuele-vertrektijden/main.link?station=Arnhem"
- /* + station */);
+ .getStatuspage("http://www.ns.nl/actuele-vertrektijden/main.link?station="
+ + station);
if (response.getHttpStatusCode() != 200) {
return Collections.emptyList();
}
Source source = new Source(response.getPageContent());
source.fullSequentialParse();
List<Train> newTrains = new ArrayList<Train>();
List<Element> tableRows = source.getAllElements(HTMLElementName.TR);
for (Element tableRow : tableRows) {
if (tableRow.getParentElement().getName().equals(
HTMLElementName.TBODY)) {
Train train = new Train();
int index = 0;
for (Element curCell : tableRow.getChildElements()) {
String contents = curCell.getTextExtractor().toString();
switch (index) {
case TIME:
setTime(train, contents);
break;
case DESTINATION:
setDestination(train, contents);
break;
case PLATFORM:
setPlatform(train, contents, curCell
.getAttributeValue("class"));
break;
case DETAILS:
setDetails(train, contents);
break;
}
index++;
}
newTrains.add(train);
}
}
return newTrains;
} catch (Exception e) {
log.error("Unable to refresh data from ns: {} {}", e.getClass()
.getSimpleName(), e.getMessage());
return Collections.emptyList();
}
}
private void setTime(Train train, String content) {
String time;
int space = content.indexOf(' ');
if (space > 0) {
time = content.substring(0, space);
try {
String delayPart = content.substring(space + 3);
train.setDelay(Integer.parseInt(delayPart.substring(0,
delayPart.indexOf(' '))));
} catch (Exception e) {
log.info("Cannot parse delay from '" + content + "': "
+ e.getMessage());
}
} else {
time = content;
}
train.setDepartureTime(time);
}
private void setDestination(Train train, String destination) {
train.setDestination(destination);
}
private void setPlatform(Train train, String platform, String classAttr) {
train.setPlatform(platform);
if (classAttr != null && classAttr.contains("highlight"))
train.setPlatformChange(true);
}
private void setDetails(Train train, String details) {
if (details.contains("Sprinter"))
train.setType(TrainType.SPRINTER);
else if (details.contains("Intercity"))
train.setType(TrainType.INTERCITY);
else if (details.contains("Sneltrein"))
train.setType(TrainType.SNELTREIN);
else if (details.contains("Stoptrein"))
train.setType(TrainType.STOPTREIN);
else if (details.contains("Int. Trein"))
train.setType(TrainType.INTERNATIONAL);
else if (details.contains("Fyra"))
train.setType(TrainType.HIGH_SPEED);
else if (details.contains("Thalys"))
train.setType(TrainType.HIGH_SPEED);
else if (details.contains("ICE"))
train.setType(TrainType.HIGH_SPEED);
else if (details.contains("Rijdt vandaag niet"))
train.setType(TrainType.CANCELED);
else
train.setType(TrainType.UNKNOWN);
}
public List<Train> getTrains(Key key) {
return trains.get(key);
}
}
| true | true | private List<Train> fetchDepartures(Key location, String station) {
try {
// StatusPageResponse response = RetrieverUtils
// .getStatuspage("http://192.168.55.113/api/json");
StatusPageResponse response = RetrieverUtils
.getStatuspage("http://www.ns.nl/actuele-vertrektijden/main.link?station=Arnhem"
/* + station */);
if (response.getHttpStatusCode() != 200) {
return Collections.emptyList();
}
Source source = new Source(response.getPageContent());
source.fullSequentialParse();
List<Train> newTrains = new ArrayList<Train>();
List<Element> tableRows = source.getAllElements(HTMLElementName.TR);
for (Element tableRow : tableRows) {
if (tableRow.getParentElement().getName().equals(
HTMLElementName.TBODY)) {
Train train = new Train();
int index = 0;
for (Element curCell : tableRow.getChildElements()) {
String contents = curCell.getTextExtractor().toString();
switch (index) {
case TIME:
setTime(train, contents);
break;
case DESTINATION:
setDestination(train, contents);
break;
case PLATFORM:
setPlatform(train, contents, curCell
.getAttributeValue("class"));
break;
case DETAILS:
setDetails(train, contents);
break;
}
index++;
}
newTrains.add(train);
}
}
return newTrains;
} catch (Exception e) {
log.error("Unable to refresh data from ns: {} {}", e.getClass()
.getSimpleName(), e.getMessage());
return Collections.emptyList();
}
}
| private List<Train> fetchDepartures(Key location, String station) {
try {
// StatusPageResponse response = RetrieverUtils
// .getStatuspage("http://192.168.55.113/api/json");
StatusPageResponse response = RetrieverUtils
.getStatuspage("http://www.ns.nl/actuele-vertrektijden/main.link?station="
+ station);
if (response.getHttpStatusCode() != 200) {
return Collections.emptyList();
}
Source source = new Source(response.getPageContent());
source.fullSequentialParse();
List<Train> newTrains = new ArrayList<Train>();
List<Element> tableRows = source.getAllElements(HTMLElementName.TR);
for (Element tableRow : tableRows) {
if (tableRow.getParentElement().getName().equals(
HTMLElementName.TBODY)) {
Train train = new Train();
int index = 0;
for (Element curCell : tableRow.getChildElements()) {
String contents = curCell.getTextExtractor().toString();
switch (index) {
case TIME:
setTime(train, contents);
break;
case DESTINATION:
setDestination(train, contents);
break;
case PLATFORM:
setPlatform(train, contents, curCell
.getAttributeValue("class"));
break;
case DETAILS:
setDetails(train, contents);
break;
}
index++;
}
newTrains.add(train);
}
}
return newTrains;
} catch (Exception e) {
log.error("Unable to refresh data from ns: {} {}", e.getClass()
.getSimpleName(), e.getMessage());
return Collections.emptyList();
}
}
|
diff --git a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
index 34a192b..36d6af8 100644
--- a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
+++ b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java
@@ -1,203 +1,205 @@
package hudson.plugins.promoted_builds.conditions;
import hudson.CopyOnWrite;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Fingerprint;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.plugins.promoted_builds.JobPropertyImpl;
import hudson.plugins.promoted_builds.PromotionBadge;
import hudson.plugins.promoted_builds.PromotionCondition;
import hudson.plugins.promoted_builds.PromotionConditionDescriptor;
import hudson.plugins.promoted_builds.PromotionProcess;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* {@link PromotionCondition} that tests if certain downstream projects have passed.
*
* @author Kohsuke Kawaguchi
*/
public class DownstreamPassCondition extends PromotionCondition {
/**
* List of downstream jobs that are used as the promotion criteria.
*
* Every job has to have at least one successful build for us to promote a build.
*/
private final String jobs;
public DownstreamPassCondition(String jobs) {
this.jobs = jobs;
}
public String getJobs() {
return jobs;
}
@Override
public PromotionBadge isMet(AbstractBuild<?,?> build) {
Badge badge = new Badge();
OUTER:
for (AbstractProject<?,?> j : getJobList()) {
for( AbstractBuild<?,?> b : build.getDownstreamBuilds(j) ) {
if(b.getResult()== Result.SUCCESS) {
badge.add(b);
continue OUTER;
}
}
// none of the builds of this job passed.
return null;
}
return badge;
}
public PromotionConditionDescriptor getDescriptor() {
return DescriptorImpl.INSTANCE;
}
/**
* List of downstream jobs that we need to monitor.
*
* @return never null.
*/
public List<AbstractProject<?,?>> getJobList() {
List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>();
for (String name : Util.tokenize(jobs,",")) {
AbstractProject job = Hudson.getInstance().getItemByFullName(name.trim(),AbstractProject.class);
if(job!=null) r.add(job);
}
return r;
}
/**
* Short-cut for {@code getJobList().contains(job)}.
*/
public boolean contains(AbstractProject<?,?> job) {
if(!jobs.contains(job.getFullName())) return false; // quick rejection test
for (String name : Util.tokenize(jobs,",")) {
if(name.trim().equals(job.getFullName()))
return true;
}
return false;
}
public static final class Badge extends PromotionBadge {
/**
* Downstream builds that certified this build. Should be considered read-only.
*/
public final List<Fingerprint.BuildPtr> builds = new ArrayList<Fingerprint.BuildPtr>();
void add(AbstractBuild<?,?> b) {
builds.add(new Fingerprint.BuildPtr(b));
}
}
public static final class DescriptorImpl extends PromotionConditionDescriptor {
public DescriptorImpl() {
super(DownstreamPassCondition.class);
new RunListenerImpl().register();
}
public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
public String getDisplayName() {
return "When the following downstream projects build successfully";
}
public String getHelpFile() {
return "/plugin/promoted-builds/conditions/downstream.html";
}
public PromotionCondition newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return new DownstreamPassCondition(formData.getString("jobs"));
}
public static final DescriptorImpl INSTANCE = new DescriptorImpl();
}
/**
* {@link RunListener} to pick up completions of downstream builds.
*
* <p>
* This is a single instance that receives all the events everywhere in the system.
* @author Kohsuke Kawaguchi
*/
private static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> {
public RunListenerImpl() {
super((Class)AbstractBuild.class);
}
@Override
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
boolean warned = false; // used to avoid warning for the same project more than once.
JobPropertyImpl jp = j.getProperty(JobPropertyImpl.class);
if(jp!=null) {
for (PromotionProcess p : jp.getItems()) {
boolean considerPromotion = false;
for (PromotionCondition cond : p.conditions) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent())) {
considerPromotion = true;
break;
}
}
}
if(considerPromotion) {
try {
AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
if(u==null) {
// no upstream build. perhaps a configuration problem?
if(build.getResult()==Result.SUCCESS && !warned) {
- listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded.");
+ listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, " +
+ "but no fingerprint is recorded. Fingerprint needs to be enabled on both this job and "+j.getFullDisplayName()+". " +
+ "See http://hudson.gotdns.com/wiki/display/HUDSON/Fingerprint for more details");
warned = true;
}
} else
if(p.considerPromotion(u))
listener.getLogger().println("Promoted "+u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
/**
* List of downstream jobs that we are interested in.
*/
@CopyOnWrite
private static volatile Set<AbstractProject> DOWNSTREAM_JOBS = Collections.emptySet();
/**
* Called whenever some {@link JobPropertyImpl} changes to update {@link #DOWNSTREAM_JOBS}.
*/
public static void rebuildCache() {
Set<AbstractProject> downstreams = new HashSet<AbstractProject>();
DOWNSTREAM_JOBS = downstreams;
}
}
}
| true | true | public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
boolean warned = false; // used to avoid warning for the same project more than once.
JobPropertyImpl jp = j.getProperty(JobPropertyImpl.class);
if(jp!=null) {
for (PromotionProcess p : jp.getItems()) {
boolean considerPromotion = false;
for (PromotionCondition cond : p.conditions) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent())) {
considerPromotion = true;
break;
}
}
}
if(considerPromotion) {
try {
AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
if(u==null) {
// no upstream build. perhaps a configuration problem?
if(build.getResult()==Result.SUCCESS && !warned) {
listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded.");
warned = true;
}
} else
if(p.considerPromotion(u))
listener.getLogger().println("Promoted "+u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
| public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) {
// this is not terribly efficient,
for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) {
boolean warned = false; // used to avoid warning for the same project more than once.
JobPropertyImpl jp = j.getProperty(JobPropertyImpl.class);
if(jp!=null) {
for (PromotionProcess p : jp.getItems()) {
boolean considerPromotion = false;
for (PromotionCondition cond : p.conditions) {
if (cond instanceof DownstreamPassCondition) {
DownstreamPassCondition dpcond = (DownstreamPassCondition) cond;
if(dpcond.contains(build.getParent())) {
considerPromotion = true;
break;
}
}
}
if(considerPromotion) {
try {
AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j);
if(u==null) {
// no upstream build. perhaps a configuration problem?
if(build.getResult()==Result.SUCCESS && !warned) {
listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, " +
"but no fingerprint is recorded. Fingerprint needs to be enabled on both this job and "+j.getFullDisplayName()+". " +
"See http://hudson.gotdns.com/wiki/display/HUDSON/Fingerprint for more details");
warned = true;
}
} else
if(p.considerPromotion(u))
listener.getLogger().println("Promoted "+u);
} catch (IOException e) {
e.printStackTrace(listener.error("Failed to promote a build"));
}
}
}
}
}
}
|
diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
index a5aba0c87..7347bad0a 100644
--- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
+++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
@@ -1,148 +1,148 @@
/**
* 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.mifosplatform.portfolio.search.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.search.data.SearchConditions;
import org.mifosplatform.portfolio.search.data.SearchData;
import org.mifosplatform.useradministration.domain.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class SearchReadPlatformServiceImpl implements SearchReadPlatformService {
private final NamedParameterJdbcTemplate namedParameterjdbcTemplate;
private final PlatformSecurityContext context;
@Autowired
public SearchReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) {
this.context = context;
this.namedParameterjdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
@Override
public Collection<SearchData> retriveMatchingData(final SearchConditions searchConditions) {
AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
SearchMapper rm = new SearchMapper();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("hierarchy", hierarchy + "%");
params.addValue("search", searchConditions.getSearchQuery());
params.addValue("partialSearch", "%" + searchConditions.getSearchQuery() + "%");
return this.namedParameterjdbcTemplate.query(rm.searchSchema(searchConditions), params, rm);
}
private static final class SearchMapper implements RowMapper<SearchData> {
public String searchSchema(final SearchConditions searchConditions) {
String union = " union all ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
- String groupExactMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
- String groupMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
@Override
public SearchData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long entityId = JdbcSupport.getLong(rs, "entityId");
final String entityAccountNo = rs.getString("entityAccountNo");
final String entityExternalId = rs.getString("entityExternalId");
final String entityName = rs.getString("entityName");
final String entityType = rs.getString("entityType");
final Long parentId = JdbcSupport.getLong(rs, "parentId");
final String parentName = rs.getString("parentName");
return new SearchData(entityId, entityAccountNo, entityExternalId, entityName, entityType, parentId, parentName);
}
}
}
| false | true | public String searchSchema(final SearchConditions searchConditions) {
String union = " union all ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
String groupExactMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
String groupMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
| public String searchSchema(final SearchConditions searchConditions) {
String union = " union all ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/RestController.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/RestController.java
index d066f7fef7c..f32a6f5f867 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/RestController.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/RestController.java
@@ -1,121 +1,123 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.path.PathTrie;
import org.elasticsearch.common.settings.Settings;
import java.io.IOException;
import static org.elasticsearch.rest.RestResponse.Status.*;
/**
* @author kimchy (shay.banon)
*/
public class RestController extends AbstractLifecycleComponent<RestController> {
private final PathTrie<RestHandler> getHandlers = new PathTrie<RestHandler>();
private final PathTrie<RestHandler> postHandlers = new PathTrie<RestHandler>();
private final PathTrie<RestHandler> putHandlers = new PathTrie<RestHandler>();
private final PathTrie<RestHandler> deleteHandlers = new PathTrie<RestHandler>();
private final PathTrie<RestHandler> headHandlers = new PathTrie<RestHandler>();
private final PathTrie<RestHandler> optionsHandlers = new PathTrie<RestHandler>();
@Inject public RestController(Settings settings) {
super(settings);
}
@Override protected void doStart() throws ElasticSearchException {
}
@Override protected void doStop() throws ElasticSearchException {
}
@Override protected void doClose() throws ElasticSearchException {
}
public void registerHandler(RestRequest.Method method, String path, RestHandler handler) {
switch (method) {
case GET:
getHandlers.insert(path, handler);
break;
case DELETE:
deleteHandlers.insert(path, handler);
break;
case POST:
postHandlers.insert(path, handler);
break;
case PUT:
putHandlers.insert(path, handler);
break;
case OPTIONS:
optionsHandlers.insert(path, handler);
+ break;
case HEAD:
headHandlers.insert(path, handler);
+ break;
default:
throw new ElasticSearchIllegalArgumentException("Can't handle [" + method + "] for path [" + path + "]");
}
}
public void dispatchRequest(final RestRequest request, final RestChannel channel) {
final RestHandler handler = getHandler(request);
if (handler == null) {
channel.sendResponse(new StringRestResponse(BAD_REQUEST, "No handler found for uri [" + request.uri() + "] and method [" + request.method() + "]"));
return;
}
try {
handler.handleRequest(request, channel);
} catch (Exception e) {
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1);
}
}
}
private RestHandler getHandler(RestRequest request) {
String path = getPath(request);
RestRequest.Method method = request.method();
if (method == RestRequest.Method.GET) {
return getHandlers.retrieve(path, request.params());
} else if (method == RestRequest.Method.POST) {
return postHandlers.retrieve(path, request.params());
} else if (method == RestRequest.Method.PUT) {
return putHandlers.retrieve(path, request.params());
} else if (method == RestRequest.Method.DELETE) {
return deleteHandlers.retrieve(path, request.params());
} else if (method == RestRequest.Method.HEAD) {
return headHandlers.retrieve(path, request.params());
} else if (method == RestRequest.Method.OPTIONS) {
return optionsHandlers.retrieve(path, request.params());
} else {
return null;
}
}
private String getPath(RestRequest request) {
return request.path();
}
}
| false | true | public void registerHandler(RestRequest.Method method, String path, RestHandler handler) {
switch (method) {
case GET:
getHandlers.insert(path, handler);
break;
case DELETE:
deleteHandlers.insert(path, handler);
break;
case POST:
postHandlers.insert(path, handler);
break;
case PUT:
putHandlers.insert(path, handler);
break;
case OPTIONS:
optionsHandlers.insert(path, handler);
case HEAD:
headHandlers.insert(path, handler);
default:
throw new ElasticSearchIllegalArgumentException("Can't handle [" + method + "] for path [" + path + "]");
}
}
| public void registerHandler(RestRequest.Method method, String path, RestHandler handler) {
switch (method) {
case GET:
getHandlers.insert(path, handler);
break;
case DELETE:
deleteHandlers.insert(path, handler);
break;
case POST:
postHandlers.insert(path, handler);
break;
case PUT:
putHandlers.insert(path, handler);
break;
case OPTIONS:
optionsHandlers.insert(path, handler);
break;
case HEAD:
headHandlers.insert(path, handler);
break;
default:
throw new ElasticSearchIllegalArgumentException("Can't handle [" + method + "] for path [" + path + "]");
}
}
|
diff --git a/src/net/derkholm/nmica/extra/app/MotifSetSummary.java b/src/net/derkholm/nmica/extra/app/MotifSetSummary.java
index 94cbdfb..b572349 100644
--- a/src/net/derkholm/nmica/extra/app/MotifSetSummary.java
+++ b/src/net/derkholm/nmica/extra/app/MotifSetSummary.java
@@ -1,982 +1,982 @@
package net.derkholm.nmica.extra.app;
import hep.aida.bin.StaticBin1D;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.derkholm.nmica.apps.MetaMotifBackgroundParameterEstimator;
import net.derkholm.nmica.build.NMExtraApp;
import net.derkholm.nmica.matrix.Matrix2D;
import net.derkholm.nmica.model.metamotif.Dirichlet;
import net.derkholm.nmica.model.metamotif.DirichletParamEstimator;
import net.derkholm.nmica.model.metamotif.IllegalAlphaParameterException;
import net.derkholm.nmica.model.metamotif.MetaMotif;
import net.derkholm.nmica.model.metamotif.MetaMotifIOTools;
import net.derkholm.nmica.motif.Motif;
import net.derkholm.nmica.motif.MotifComparitorIFace;
import net.derkholm.nmica.motif.MotifIOTools;
import net.derkholm.nmica.motif.MotifPair;
import net.derkholm.nmica.motif.MotifTools;
import net.derkholm.nmica.motif.SquaredDifferenceMotifComparitor;
import net.derkholm.nmica.motif.align.MotifAlignment;
import net.derkholm.nmica.motif.align.NoPositionFoundException;
import net.derkholm.nmica.seq.WmTools;
import org.biojava.bio.dist.Distribution;
import org.biojava.bio.dist.DistributionTools;
import org.biojava.bio.dist.UniformDistribution;
import org.biojava.bio.dp.SimpleWeightMatrix;
import org.biojava.bio.dp.WeightMatrix;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.symbol.AlphabetIndex;
import org.biojava.bio.symbol.AlphabetManager;
import org.biojava.bio.symbol.FiniteAlphabet;
import org.biojava.bio.symbol.Symbol;
import org.bjv2.util.cli.App;
import org.bjv2.util.cli.Option;
import org.bjv2.util.cli.UserLevel;
import cern.colt.list.DoubleArrayList;
@App(overview = "Calculate summary statistics for motif sets", generateStub = true)
@NMExtraApp(launchName = "nmmotifsum")
public class MotifSetSummary {
private static final double VERY_NEGATIVE_DOUBLE = -500000000.0;
private Motif[] motifs;
private Motif[] otherMotifs;
private boolean perColAvgEntropy;
private boolean avgLength;
private boolean num;
private MetaMotif[] metamotifs;
private MotifComparitorIFace mc = SquaredDifferenceMotifComparitor.getMotifComparitor();
private boolean length = false;
private boolean perMotifAvgEntropy = false;
private double threshold = Double.POSITIVE_INFINITY;
private boolean gcContent = false;
private boolean palindromicity = false;
private boolean bg = false;
private double maxAlphaSum = 50;
private double pseudoCount = 0;
private boolean reportAvgDiff;
private boolean bestHits;
private boolean bestReciprocalHits;
private String[] motifsFilenames;
private String[] otherMotifsFilenames;
private boolean calcAll;
private boolean showName = true;
private boolean printHeader = true;
private boolean reportKD;
private boolean pairedOutput = true;
private boolean perColEntropy;
private String separator = " ";
private boolean calcAvgMetaMotifScore = true;
private boolean calcMaxMetaMotifScore = true;
private boolean perMotifTotalEntropy;
private int[] indices;
private boolean merged;
private int minColPerPos = 2;
HashMap<MetaMotif, File> metaMotifToFileMap = new HashMap<MetaMotif, File>();
HashMap<Motif, File> otherMotifToFileMap = new HashMap<Motif, File>();
private File outputAlignedFile;
private int maxHeaderColWidth = 192;
@Option(help = "Input motif set file(s)")
public void setMotifs(File[] files) throws Exception {
List<Motif> motifList = new ArrayList<Motif>();
for (File f : files) {
Motif[] ms = MotifIOTools.loadMotifSetXML(
new BufferedInputStream(new FileInputStream(f)));
for (Motif m : ms)
motifList.add(m);
}
this.motifs = motifList.toArray(new Motif[motifList.size()]);
/*
this.motifsFilenames = new String[this.motifs.length];
for (int i = 0; i < this.motifsFilenames.length; i++) {
this.motifsFilenames[i] = files[i].getName();
}*/
}
@Option(help = "Calculate the average score with each of the metamotifs " +
"(sum probabilities with all alignments of motif X with metamotif X, " +
"divided by the length of the motif) (default=true)",
optional=true)
public void setAvgMetaMotifScore(boolean b) {
this.calcAvgMetaMotifScore = b;
}
@Option(help = "Calculate the maximum score with each of the metamotifs",
optional=true)
public void setMaxMetaMotifScore(boolean b) {
this.calcMaxMetaMotifScore = b;
}
@Option(help = "Other motif set file(s) to compare those given with -motifs", optional=true)
public void setOtherMotifs(File[] files) throws Exception {
List<Motif> motifList = new ArrayList<Motif>();
for (File f : files) {
System.err.printf("Reading file %s%n",f.getPath());
Motif[] ms = MotifIOTools.loadMotifSetXML(
new BufferedInputStream(new FileInputStream(f)));
for (Motif m : ms) {
motifList.add(m);
otherMotifToFileMap.put(m,f);
}
}
this.otherMotifs = motifList.toArray(new Motif[motifList.size()]);
/*
this.otherMotifsFilenames = new String[this.otherMotifs.length];
for (int i = 0; i < this.otherMotifsFilenames.length; i++) {
this.otherMotifsFilenames[i] = files[i].getName();
}*/
}
@Option(help="Calculate KD divergences", optional=true)
public void setKD(boolean b) {
this.reportKD = b;
}
@Option(help="Field separator (options:space|tab)", optional=true, userLevel = UserLevel.EXPERT)
public void setSep(String sep) {
if (sep.equals("space")) {
this.separator = " ";
} else if (sep.equals("tab")) {
this.separator = "\t";
} else {
System.err.printf("Invalid separator '%s' given. Allowed values: space,tab %n");
System.exit(1);
}
}
@Option(help = "Calculate all per-motif qualities",optional=true)
public void setAll(boolean b) {
this.calcAll = b;
}
@Option(help = "Show motif name",optional=true)
public void setName(boolean b) {
this.showName = b;
}
@Option(help = "Add pseudocounts",optional=true)
public void setPseudoCount(double d) {
this.pseudoCount = d;
}
@Option(help = "Output as paired distances (default) " +
"rather than as a distance matrix",optional=true)
public void setPairedOutput(boolean b) {
this.pairedOutput = b;
}
@Option(help = "Input metamotif set file(s) for hit seeking",optional=true)
public void setMetaMotifs(File[] files) throws Exception {
List<MetaMotif> metamotifList = new ArrayList<MetaMotif>();
for (File f : files) {
System.err.printf("Reading metamotif file %s%n",f.getPath());
try {
MetaMotif[] ms = MetaMotifIOTools.loadMetaMotifSetXML(
new BufferedInputStream(new FileInputStream(f)));
for (MetaMotif m : ms) {
metamotifList.add(m);
metaMotifToFileMap.put(m,f);
}
} catch (Exception e) {
System.err.println("Reading input metamotif set " + f.getName() + " failed.");
System.err.println(e);
System.exit(1);
}
}
if (metamotifList.size() == 0) {
System.out.println("No metamotifs were given.");
System.exit(1);
}
this.metamotifs = metamotifList.toArray(new MetaMotif[metamotifList.size()]);
}
@Option(help = "Report average entropy of the motif set (per column)", optional=true)
public void setColwiseAvgEntropy(boolean b) {
this.perColAvgEntropy = b;
}
@Option(help = "Report entropy of the motif set for each motif column", optional=true)
public void setColwiseEntropy(boolean b) {
this.perColEntropy = b;
}
@Option(help = "Report total entropy for each motif", optional=true)
public void setPerMotifTotalEntropy(boolean b) {
this.perMotifTotalEntropy = b;
}
@Option(help = "Report average entropy for each motif", optional=true)
public void setPerMotifAvgEntropy(boolean b) {
this.perMotifAvgEntropy = b;
}
@Option(help = "Report CG content", optional=true)
public void setGcContent(boolean b) {
this.gcContent = b;
}
//FIXME: Get this from TransCrypt!
@Option(help = "Report palindromicity", optional=true)
public void setPalindromicity(boolean b) {
this.palindromicity = b;
}
@Option(help = "Max alpha sum for the metamotif columns " +
"(others will be clamped to this value)", optional=true)
public void setMaxAlphaSum(double d) {
this.maxAlphaSum = d;
}
@Option(help = "Report best hits between motif sets", optional=true)
public void setBestHits(boolean b) {
this.bestHits = b;
}
@Option(help = "Report best reciprocal hits between motif sets", optional=true)
public void setBestReciprocalHits(boolean b) {
this.bestReciprocalHits = b;
}
@Option(help = "Report length", optional=true)
public void setLength(boolean b) {
this.length = b;
}
@Option(help = "Report background params", optional=true)
public void setBg(boolean b) {
this.bg = b;
}
@Option(help = "Report average length", optional=true)
public void setAvgLength(boolean b) {
this.avgLength = b;
}
@Option(help = "Print out a header row to the feature table", optional=true)
public void setHeader(boolean b) {
this.printHeader = b;
}
@Option(help = "Report number of motifs in the set", optional=true)
public void setNum(boolean b) {
this.num = b;
}
@Option(help = "Report average difference with the other motif set", optional=true)
public void setAvgDiff(boolean b) {
this.reportAvgDiff = b;
}
@Option(help = "Calculate the summary for the motifs at the selected indices only", optional = true)
public void setAtIndex(int[] indices) {
this.indices = indices;
}
@Option(help = "Align input motifs and merge the alignment (average motif), " +
"calculate summary from this merged motif", optional = true)
public void setMerged(boolean b) {
this.merged = b;
}
@Option(help="Minimum number of columns per position in the merged motif (default=2, only used in conjunction with -merged)",optional=true)
public void setMinCols(int i) {
this.minColPerPos = i;
}
@Option(help="Output aligned input motifs", userLevel = UserLevel.DEBUG, optional=true)
public void setOutputAligned(File f) {
this.outputAlignedFile = f;
}
@Option(help="Maximum header column width in characters (default = 192)", optional=true, userLevel = UserLevel.DEBUG)
public void setMaxHeaderColWidth(int i) {
this.maxHeaderColWidth = i;
}
//no need to make this configurable
//@Option(help="Metamotif name in header field name")
//public void setMetamotifName(boolean b) {
// this.metaMotifNameInHeader = b;
//}
public void main(String[] args) throws Exception {
if (calcAll) {
length = true;
perMotifAvgEntropy = true;
perMotifTotalEntropy = true;
gcContent = true;
palindromicity = true;
bg = true;
}
if (indices != null) {
Motif[] selMotifs = new Motif[indices.length];
for (int i = 0; i < indices.length; i++) {
selMotifs[i] = motifs[indices[i]];
}
motifs = selMotifs;
}
if (merged && (motifs.length > 1)) {
MotifAlignment alignment = new MotifAlignment(motifs, mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = alignment.alignmentWithZeroOffset();
if (outputAlignedFile != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(new FileOutputStream(outputAlignedFile)),
new Motif[] {alignment.averageMotif()});
}
try {
alignment = alignment.trimToColumnsPerPosition(minColPerPos);
} catch (NoPositionFoundException e) {
System.err.printf(
"WARNING! No position was found with at least %d columns. " +
"Will output the alignment without trimming.", minColPerPos);
}
motifs = new Motif[] {alignment.averageMotif()};
}
if (pseudoCount > 0) {
for (Motif m : motifs)
MotifTools.addPseudoCounts(m,pseudoCount);
if (otherMotifs != null)
for (Motif m : otherMotifs)
MotifTools.addPseudoCounts(m, pseudoCount);
} if (pseudoCount < 0) {
System.out.println(
"ERROR: -pseudoCount = " +
pseudoCount +
" + (nonnegative value required)");
System.exit(1);
}
if (maxAlphaSum > 0 && metamotifs != null) {
for (MetaMotif m : metamotifs) {
for (int i = 0; i < m.columns(); i++) {
Dirichlet dd = m.getColumn(i);
if (dd.alphaSum() > maxAlphaSum) {
dd.scaleAlphaSum(maxAlphaSum / dd.alphaSum());
}
}
}
}
if (perColEntropy) {
Distribution[] allDists = allDists();
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
System.out.println(entropyElsewhere);
for (Motif m : motifs)
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
System.out.println(m.getName() + separator +
i + separator +
(entropyElsewhere -
DistributionTools.totalEntropy(
m.getWeightMatrix().getColumn(i))));
}
System.exit(0);
}
if (perColAvgEntropy) {
Distribution[] allDists = allDists();
double[] entropies = new double[allDists.length];
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
for (int i = 0; i < entropies.length; i++)
entropies[i] = entropyElsewhere - DistributionTools.totalEntropy(allDists[i]);
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(entropies));
System.out.println(bin.mean());
System.exit(0);
}
double[] allEntropies = new double[this.motifs.length];
double[] allLengths = new double[this.motifs.length];
double[] allTotalEntropies = new double[this.motifs.length];
if (perMotifAvgEntropy ||
perMotifTotalEntropy) {
int mI = 0;
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
for (Motif m : this.motifs) {
allTotalEntropies[mI] = MotifSetSummary.weightMatrixTotalEntropy(m.getWeightMatrix(), elsewhere);
allEntropies[mI++] = MotifSetSummary.weightMatrixAverageColumnEntropy(m.getWeightMatrix(), elsewhere);
}
}
if (length) {
int mI = 0;
for (Motif m : this.motifs) {
allLengths[mI++] = m.getWeightMatrix().columns();
}
}
double[][] metaMotifBestHits = new double[this.motifs.length][];
double[][] metaMotifAvgHits = new double[this.motifs.length][];
double[][] otherMotifBestHits = new double[this.motifs.length][];
List<String> headerCols = new ArrayList<String>();
if (bestHits || bestReciprocalHits) {
if (bestHits && bestReciprocalHits) {
System.err.println("-bestHits and -bestReciprocalHits are exclusive");
System.exit(1);
}
}
if (bestHits) {
if (otherMotifs != null) {
//paired output cannot be combined with calculating other motifs.
if (pairedOutput) {
MotifPair[] mpairs = SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHits(motifs, otherMotifs);
if (printHeader) {
System.out.println("motif1" + separator + "motif2" + separator + "score");
}
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
//not paired output with other motifs = table of distances with each column being one of the 'other' motifs
else {
System.err.println("Not paired output");
Matrix2D motifDistances =
SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHitsMatrix(motifs, otherMotifs);
System.err.printf("rows: %d cols: %d%n", motifDistances.rows(), motifDistances.columns());
for (int i = 0; i < motifDistances.rows(); i++) {
System.err.printf("Row: %d columns: %d%n", i, motifDistances.columns());
otherMotifBestHits[i] = new double[motifDistances.columns()];
for (int j = 0; j < motifDistances.columns(); j++) {
double d = motifDistances.get(i, j);
otherMotifBestHits[i][j] = d;
}
}
}
}
//print the distance matrix of motifs against themselves
//again, a separate output mode from all the rest,
//cannot be combined with calculating other features
else {
printSelfSimilaryMatrix(motifs, separator);
//exit because can't be combine with other output forms
System.exit(0);
}
}
if (bestReciprocalHits) {
MotifPair[] mpairs =
SquaredDifferenceMotifComparitor
.getMotifComparitor()
.bestReciprocalHits(motifs, otherMotifs);
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
/*
* Why not score them with the 1D dynamic programming based tiling of metamotifs that
* you can actually fit in that motif?
*/
if (metamotifs != null) {
for (int i = 0; i < motifs.length; i++) {
Motif m = motifs[i];
metaMotifBestHits[i] = new double[metamotifs.length];
metaMotifAvgHits[i] = new double[metamotifs.length];
for (int j = 0; j < metamotifs.length; j++) {
MetaMotif mm = metamotifs[j];
double[] probs = null;
if (mm.columns() <= m.getWeightMatrix().columns())
probs = mm.logProbDensities(m.getWeightMatrix());
if (probs != null) {
StaticBin1D bin = new StaticBin1D();
for (double d : probs)
if (!Double.isInfinite(d) && !Double.isNaN(d))
bin.add(d);
if (bin.size() > 0) {
metaMotifAvgHits[i][j] = bin.mean();
metaMotifBestHits[i][j] = bin.max();
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
}
}
}
double[] palindromicities = new double[motifs.length];
double[] gappedPalindromicities1 = new double[motifs.length];
double[] gappedPalindromicities2 = new double[motifs.length];
double[] gappedPalindromicities3 = new double[motifs.length];
double[] selfRepeatednesses = new double[motifs.length];
if (palindromicity) {
for (int m = 0; m < palindromicities.length; m++) {
palindromicities[m] = howPalindromic(motifs[m]);
gappedPalindromicities1[m] = howGappedPalindromic(motifs[m], 1);
gappedPalindromicities2[m] = howGappedPalindromic(motifs[m], 2);
gappedPalindromicities3[m] = howGappedPalindromic(motifs[m], 3);
selfRepeatednesses[m] = howSelfRepeating(motifs[m]);
}
}
double[] gcContents = new double[this.motifs.length];
if (gcContent) {
for (int m = 0; m < this.motifs.length; m++) {
double gc = 0;
double total = 0;
for (int i = 0, cols = motifs[m].getWeightMatrix().columns(); i < cols; i++) {
Distribution distrib = motifs[m].getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
if (sym.equals(DNATools.g()) || sym.equals(DNATools.c())){
gc = gc + distrib.getWeight(sym);
}
total = distrib.getWeight(sym);
}
}
gcContents[m] = gc / total;
}
}
if (avgLength) {
double[] lengths = new double[motifs.length];
for (int i = 0; i < lengths.length; i++)
lengths[i] = motifs[i].getWeightMatrix().columns();
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(lengths));
System.out.println(bin.mean());
System.exit(0);
}
if (num) {
System.out.println(motifs.length);
System.exit(0);
}
double avgDiff = 0.0;
FiniteAlphabet alphab = (FiniteAlphabet) this.motifs[0].getWeightMatrix().getAlphabet();
double[] symmBGParams = new double[motifs.length];
double[][] asymmBGParams = new double[motifs.length][alphab.size()];
AlphabetIndex alphabIndex = AlphabetManager.getAlphabetIndex(alphab);
if (bg) {
for (int m = 0; m < motifs.length; m++) {
Distribution[] ds = new Distribution[motifs[m].getWeightMatrix().columns()];
for (int i = 0; i < ds.length; i++) {
ds[i] = motifs[m].getWeightMatrix().getColumn(i);
}
Dirichlet dd;
try {
dd = DirichletParamEstimator.mle(ds,0.01);
} catch (IllegalAlphaParameterException e) {
System.err.printf(
"Could not estimate background for motif %s", motifs[m].getName());
dd = new Dirichlet((FiniteAlphabet)motifs[m].getWeightMatrix().getAlphabet());
}
Dirichlet symmDD = MetaMotifBackgroundParameterEstimator
.symmetricDirichlet(ds, 0.1, 10, 0.01);
for (int i = 0; i < asymmBGParams[m].length; i++) {
asymmBGParams[m][i] = dd.getWeight(alphabIndex.symbolForIndex(i));
}
//Symmetric, all weights the same --> let's just take the first one
symmBGParams[m] = symmDD.getWeight(alphabIndex.symbolForIndex(0));
}
}
if (showName) headerCols.add("name");
if (length) headerCols.add("length");
if (perMotifAvgEntropy) headerCols.add("avg-entropy");
if (perMotifTotalEntropy) headerCols.add("total-entropy");
if (palindromicity) {
headerCols.add("pal0");
headerCols.add("pal1");
headerCols.add("pal2");
headerCols.add("pal3");
headerCols.add("selfrep");
}
if (bg) {
headerCols.add("bgsymm");
headerCols.add("bg_asymm_1");
headerCols.add("bg_asymm_2");
headerCols.add("bg_asymm_3");
headerCols.add("bg_asymm_4");
}
if (otherMotifs != null) {
for (int m = 0; m < otherMotifs.length; m++) {
headerCols.add("besthit_" + otherMotifs[m].getName() + "(" + otherMotifToFileMap.get(otherMotifs[m].getName()) + ")");
}
}
if (metamotifs != null) {
if (calcAvgMetaMotifScore == false && calcMaxMetaMotifScore == false) {
System.err.println("");
System.exit(1);
}
if (calcAvgMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitavg_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
if (calcMaxMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitmax_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
}
if (printHeader) {
//first cap the header column lengths (so R doesn't complain...)
for (int i = 0; i < headerCols.size(); i++) {
String str = headerCols.get(i);
if (str.length() >= maxHeaderColWidth) {
str = str.substring(0,maxHeaderColWidth);
headerCols.set(i, str);
}
}
for (int i = 0; i < headerCols.size(); i++) {
if (i < (headerCols.size() - 1))
System.out.print(headerCols.get(i) + separator);
else
System.out.print(headerCols.get(i) + "\n");
}
}
for (int m = 0; m < motifs.length; m++) {
Motif mot = motifs[m];
boolean somethingPrinted = false;
if (showName) {
System.out.print(mot.getName());
somethingPrinted = true;
}
if (length) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allLengths[m] + separator);
somethingPrinted = true;
}
if (perMotifAvgEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allEntropies[m]);
somethingPrinted = true;
}
if (perMotifTotalEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allTotalEntropies[m]);
somethingPrinted = true;
}
if (palindromicity) {
if (somethingPrinted) System.out.print(separator);
System.out.print(gappedPalindromicities1[m] + separator);
System.out.print(gappedPalindromicities2[m] + separator);
System.out.print(gappedPalindromicities3[m] + separator);
System.out.print(selfRepeatednesses[m] + separator);
somethingPrinted = true;
}
if (bg) {
if (somethingPrinted) System.out.print(separator);
- System.out.println(symmBGParams[m] + separator);
+ System.out.print(symmBGParams[m] + separator);
for (int i = 0; i < alphab.size(); i++) {
if (i < (alphab.size()-1)) {
System.out.print(asymmBGParams[m][i] + separator);
} else {
System.out.print(asymmBGParams[m][i]);
}
}
somethingPrinted = true;
}
if (otherMotifs != null &! pairedOutput) {
if (somethingPrinted) System.out.print(separator);
for (int n = 0; n < otherMotifs.length; n++) {
System.err.printf("m:%d n:%d obj:%s%n",m,n,otherMotifBestHits.toString());
if (n < (otherMotifs.length-1)) {
System.out.print(otherMotifBestHits[m][n] + separator);
} else {
System.out.print(otherMotifBestHits[m][n]);
}
}
somethingPrinted = true;
}
if (metamotifs != null) {
if (somethingPrinted) System.out.print(separator);
for (int mm = 0; mm < metamotifs.length; mm++) {
if (calcAvgMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifAvgHits[m][mm] + separator);
else
System.out.print(metaMotifAvgHits[m][mm]);
}
if (calcMaxMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifBestHits[m][mm] + separator);
else
System.out.print(metaMotifBestHits[m][mm]);
}
}
somethingPrinted = true;
}
System.out.println();
}
}
private void printSelfSimilaryMatrix(Motif[] motifs, String separator) throws Exception {
Matrix2D motifDistances =
SquaredDifferenceMotifComparitor.getMotifComparitor().bestHitsMatrix(motifs);
//header
for (int i = 0; i < motifs.length; i++) {
String namestr = motifs[i].getName();
if (namestr.length() >= maxHeaderColWidth) {
namestr = namestr.substring(0,maxHeaderColWidth);
}
System.out.print(separator+namestr);
}
System.out.println();
for (int i = 0; i < motifDistances.rows(); i++) {
//print out the motif name and then iterate
System.out.print(motifs[i].getName() + separator);
for (int j = 0; j < motifDistances.columns(); j++) {
double d = motifDistances.get(i, j);
if (j < (motifDistances.columns()-1))
System.out.print(d + separator);
else
System.out.print(d + "\n");
}
}
}
public static double weightMatrixAverageColumnEntropy(
WeightMatrix weightMatrix, Distribution elsewhere) {
double[] entropies = new double[weightMatrix.columns()];
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
for (int i = 0; i < entropies.length; i++) {
Distribution distribution = weightMatrix.getColumn(i);
entropies[i] = entropyElsewhere - DistributionTools.totalEntropy(distribution);
}
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(entropies));
return bin.mean();
}
public static double weightMatrixTotalEntropy(WeightMatrix weightMatrix, Distribution elsewhere) {
double[] entropies = new double[weightMatrix.columns()];
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
for (int i = 0; i < entropies.length; i++) {
Distribution distribution = weightMatrix.getColumn(i);
entropies[i] = entropyElsewhere - DistributionTools.totalEntropy(distribution);
}
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(entropies));
return bin.sum();
}
private Distribution[] allDists() {
List<Distribution> dists = new ArrayList<Distribution>();
for (Motif m : motifs)
for (int i = 0; i < m.getWeightMatrix().columns(); i++)
dists.add(m.getWeightMatrix().getColumn(i));
return dists.toArray(new Distribution[dists.size()]);
}
private static double div(Distribution d0, Distribution d1) throws Exception {
double cScore = 0.0;
for (Iterator i = ((FiniteAlphabet) d0.getAlphabet()).iterator(); i.hasNext(); ) {
Symbol s= (Symbol) i.next();
cScore += Math.pow(d0.getWeight(s) - d1.getWeight(s), 2.0);
}
// return Math.sqrt(cScore);
// return cScore;
return Math.pow(cScore, 2.5 / 2.0);
}
public static double compareMotifs(WeightMatrix wm0,
Distribution pad0,
WeightMatrix wm1,
Distribution pad1)
throws Exception {
double bestScore = Double.POSITIVE_INFINITY;
int minPos = -wm1.columns();
int maxPos = wm0.columns() + wm1.columns();
for (int offset = -wm1.columns(); offset <= wm0.columns(); ++offset) {
double score = 0.0;
for (int pos = minPos; pos <= maxPos; ++pos) {
Distribution col0 = pad0, col1 = pad1;
if (pos >= 0 && pos < wm0.columns()) {
col0 = wm0.getColumn(pos);
}
int opos = pos - offset;
if (opos >= 0 && opos < wm1.columns()) {
col1 = wm1.getColumn(opos);
}
double cScore = div(col0, col1);
score += cScore;
}
bestScore = Math.min(score, bestScore);
}
return bestScore;
}
//TODO: Use howPalindromic
//TODO: Use howSelfRepeating
//FIXME: Implement howSelfRepeating which allows you to tell the periodicity of repeating
//TODO: Use howGappedPalindromic
public static double howPalindromic(Motif m) throws Exception {
WeightMatrix wmOrig = m.getWeightMatrix();
WeightMatrix[] wms = splitInTwo(wmOrig,0);
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)wmOrig.getAlphabet());
return compareMotifs(
wms[0], elsewhere,
WmTools.reverseComplement(wms[1]),
elsewhere);
}
public static double howSelfRepeating(Motif m) throws Exception {
WeightMatrix wmOrig = m.getWeightMatrix();
WeightMatrix[] wms = splitInTwo(wmOrig,0);
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)wmOrig.getAlphabet());
return compareMotifs(wms[0], elsewhere, wms[1], elsewhere);
}
public static double howGappedPalindromic(Motif m, int gap) throws Exception {
WeightMatrix wmOrig = m.getWeightMatrix();
WeightMatrix[] wms = splitInTwo(wmOrig,gap);
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)wmOrig.getAlphabet());
return compareMotifs(wms[0], elsewhere, wms[1], elsewhere);
}
public static WeightMatrix[] splitInTwo(WeightMatrix wm, int gap) throws Exception {
WeightMatrix[] wms = new SimpleWeightMatrix[2];
Distribution[] dists1,dists2;
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)wm.getAlphabet());
//TODO: Figure out how to generalise this
if (wm.columns() % 2 == 0) {
dists1 = new Distribution[wm.columns()/2];
dists2 = new Distribution[wm.columns()/2];
} else {
dists1 = new Distribution[wm.columns()/2];
dists2 = new Distribution[wm.columns()/2+1];
}
for (int i=0; i < wm.columns()/2;i++) {
if (i <= wm.columns()/2 - gap) {
dists1[i] = wm.getColumn(i);
} else {
dists1[i] = elsewhere;
}
}
for (int i=wm.columns()/2; i < wm.columns(); i++) {
//dists2[i] = wm.getColumn(i);
if (i >= wm.columns()/2 + gap) {
dists2[i-wm.columns()/2] = wm.getColumn(i);
} else {
dists2[i-wm.columns()/2] = elsewhere;
}
}
wms[0] = new SimpleWeightMatrix(dists1);
wms[1] = new SimpleWeightMatrix(dists2);
return wms;
}
}
| true | true | public void main(String[] args) throws Exception {
if (calcAll) {
length = true;
perMotifAvgEntropy = true;
perMotifTotalEntropy = true;
gcContent = true;
palindromicity = true;
bg = true;
}
if (indices != null) {
Motif[] selMotifs = new Motif[indices.length];
for (int i = 0; i < indices.length; i++) {
selMotifs[i] = motifs[indices[i]];
}
motifs = selMotifs;
}
if (merged && (motifs.length > 1)) {
MotifAlignment alignment = new MotifAlignment(motifs, mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = alignment.alignmentWithZeroOffset();
if (outputAlignedFile != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(new FileOutputStream(outputAlignedFile)),
new Motif[] {alignment.averageMotif()});
}
try {
alignment = alignment.trimToColumnsPerPosition(minColPerPos);
} catch (NoPositionFoundException e) {
System.err.printf(
"WARNING! No position was found with at least %d columns. " +
"Will output the alignment without trimming.", minColPerPos);
}
motifs = new Motif[] {alignment.averageMotif()};
}
if (pseudoCount > 0) {
for (Motif m : motifs)
MotifTools.addPseudoCounts(m,pseudoCount);
if (otherMotifs != null)
for (Motif m : otherMotifs)
MotifTools.addPseudoCounts(m, pseudoCount);
} if (pseudoCount < 0) {
System.out.println(
"ERROR: -pseudoCount = " +
pseudoCount +
" + (nonnegative value required)");
System.exit(1);
}
if (maxAlphaSum > 0 && metamotifs != null) {
for (MetaMotif m : metamotifs) {
for (int i = 0; i < m.columns(); i++) {
Dirichlet dd = m.getColumn(i);
if (dd.alphaSum() > maxAlphaSum) {
dd.scaleAlphaSum(maxAlphaSum / dd.alphaSum());
}
}
}
}
if (perColEntropy) {
Distribution[] allDists = allDists();
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
System.out.println(entropyElsewhere);
for (Motif m : motifs)
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
System.out.println(m.getName() + separator +
i + separator +
(entropyElsewhere -
DistributionTools.totalEntropy(
m.getWeightMatrix().getColumn(i))));
}
System.exit(0);
}
if (perColAvgEntropy) {
Distribution[] allDists = allDists();
double[] entropies = new double[allDists.length];
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
for (int i = 0; i < entropies.length; i++)
entropies[i] = entropyElsewhere - DistributionTools.totalEntropy(allDists[i]);
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(entropies));
System.out.println(bin.mean());
System.exit(0);
}
double[] allEntropies = new double[this.motifs.length];
double[] allLengths = new double[this.motifs.length];
double[] allTotalEntropies = new double[this.motifs.length];
if (perMotifAvgEntropy ||
perMotifTotalEntropy) {
int mI = 0;
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
for (Motif m : this.motifs) {
allTotalEntropies[mI] = MotifSetSummary.weightMatrixTotalEntropy(m.getWeightMatrix(), elsewhere);
allEntropies[mI++] = MotifSetSummary.weightMatrixAverageColumnEntropy(m.getWeightMatrix(), elsewhere);
}
}
if (length) {
int mI = 0;
for (Motif m : this.motifs) {
allLengths[mI++] = m.getWeightMatrix().columns();
}
}
double[][] metaMotifBestHits = new double[this.motifs.length][];
double[][] metaMotifAvgHits = new double[this.motifs.length][];
double[][] otherMotifBestHits = new double[this.motifs.length][];
List<String> headerCols = new ArrayList<String>();
if (bestHits || bestReciprocalHits) {
if (bestHits && bestReciprocalHits) {
System.err.println("-bestHits and -bestReciprocalHits are exclusive");
System.exit(1);
}
}
if (bestHits) {
if (otherMotifs != null) {
//paired output cannot be combined with calculating other motifs.
if (pairedOutput) {
MotifPair[] mpairs = SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHits(motifs, otherMotifs);
if (printHeader) {
System.out.println("motif1" + separator + "motif2" + separator + "score");
}
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
//not paired output with other motifs = table of distances with each column being one of the 'other' motifs
else {
System.err.println("Not paired output");
Matrix2D motifDistances =
SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHitsMatrix(motifs, otherMotifs);
System.err.printf("rows: %d cols: %d%n", motifDistances.rows(), motifDistances.columns());
for (int i = 0; i < motifDistances.rows(); i++) {
System.err.printf("Row: %d columns: %d%n", i, motifDistances.columns());
otherMotifBestHits[i] = new double[motifDistances.columns()];
for (int j = 0; j < motifDistances.columns(); j++) {
double d = motifDistances.get(i, j);
otherMotifBestHits[i][j] = d;
}
}
}
}
//print the distance matrix of motifs against themselves
//again, a separate output mode from all the rest,
//cannot be combined with calculating other features
else {
printSelfSimilaryMatrix(motifs, separator);
//exit because can't be combine with other output forms
System.exit(0);
}
}
if (bestReciprocalHits) {
MotifPair[] mpairs =
SquaredDifferenceMotifComparitor
.getMotifComparitor()
.bestReciprocalHits(motifs, otherMotifs);
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
/*
* Why not score them with the 1D dynamic programming based tiling of metamotifs that
* you can actually fit in that motif?
*/
if (metamotifs != null) {
for (int i = 0; i < motifs.length; i++) {
Motif m = motifs[i];
metaMotifBestHits[i] = new double[metamotifs.length];
metaMotifAvgHits[i] = new double[metamotifs.length];
for (int j = 0; j < metamotifs.length; j++) {
MetaMotif mm = metamotifs[j];
double[] probs = null;
if (mm.columns() <= m.getWeightMatrix().columns())
probs = mm.logProbDensities(m.getWeightMatrix());
if (probs != null) {
StaticBin1D bin = new StaticBin1D();
for (double d : probs)
if (!Double.isInfinite(d) && !Double.isNaN(d))
bin.add(d);
if (bin.size() > 0) {
metaMotifAvgHits[i][j] = bin.mean();
metaMotifBestHits[i][j] = bin.max();
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
}
}
}
double[] palindromicities = new double[motifs.length];
double[] gappedPalindromicities1 = new double[motifs.length];
double[] gappedPalindromicities2 = new double[motifs.length];
double[] gappedPalindromicities3 = new double[motifs.length];
double[] selfRepeatednesses = new double[motifs.length];
if (palindromicity) {
for (int m = 0; m < palindromicities.length; m++) {
palindromicities[m] = howPalindromic(motifs[m]);
gappedPalindromicities1[m] = howGappedPalindromic(motifs[m], 1);
gappedPalindromicities2[m] = howGappedPalindromic(motifs[m], 2);
gappedPalindromicities3[m] = howGappedPalindromic(motifs[m], 3);
selfRepeatednesses[m] = howSelfRepeating(motifs[m]);
}
}
double[] gcContents = new double[this.motifs.length];
if (gcContent) {
for (int m = 0; m < this.motifs.length; m++) {
double gc = 0;
double total = 0;
for (int i = 0, cols = motifs[m].getWeightMatrix().columns(); i < cols; i++) {
Distribution distrib = motifs[m].getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
if (sym.equals(DNATools.g()) || sym.equals(DNATools.c())){
gc = gc + distrib.getWeight(sym);
}
total = distrib.getWeight(sym);
}
}
gcContents[m] = gc / total;
}
}
if (avgLength) {
double[] lengths = new double[motifs.length];
for (int i = 0; i < lengths.length; i++)
lengths[i] = motifs[i].getWeightMatrix().columns();
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(lengths));
System.out.println(bin.mean());
System.exit(0);
}
if (num) {
System.out.println(motifs.length);
System.exit(0);
}
double avgDiff = 0.0;
FiniteAlphabet alphab = (FiniteAlphabet) this.motifs[0].getWeightMatrix().getAlphabet();
double[] symmBGParams = new double[motifs.length];
double[][] asymmBGParams = new double[motifs.length][alphab.size()];
AlphabetIndex alphabIndex = AlphabetManager.getAlphabetIndex(alphab);
if (bg) {
for (int m = 0; m < motifs.length; m++) {
Distribution[] ds = new Distribution[motifs[m].getWeightMatrix().columns()];
for (int i = 0; i < ds.length; i++) {
ds[i] = motifs[m].getWeightMatrix().getColumn(i);
}
Dirichlet dd;
try {
dd = DirichletParamEstimator.mle(ds,0.01);
} catch (IllegalAlphaParameterException e) {
System.err.printf(
"Could not estimate background for motif %s", motifs[m].getName());
dd = new Dirichlet((FiniteAlphabet)motifs[m].getWeightMatrix().getAlphabet());
}
Dirichlet symmDD = MetaMotifBackgroundParameterEstimator
.symmetricDirichlet(ds, 0.1, 10, 0.01);
for (int i = 0; i < asymmBGParams[m].length; i++) {
asymmBGParams[m][i] = dd.getWeight(alphabIndex.symbolForIndex(i));
}
//Symmetric, all weights the same --> let's just take the first one
symmBGParams[m] = symmDD.getWeight(alphabIndex.symbolForIndex(0));
}
}
if (showName) headerCols.add("name");
if (length) headerCols.add("length");
if (perMotifAvgEntropy) headerCols.add("avg-entropy");
if (perMotifTotalEntropy) headerCols.add("total-entropy");
if (palindromicity) {
headerCols.add("pal0");
headerCols.add("pal1");
headerCols.add("pal2");
headerCols.add("pal3");
headerCols.add("selfrep");
}
if (bg) {
headerCols.add("bgsymm");
headerCols.add("bg_asymm_1");
headerCols.add("bg_asymm_2");
headerCols.add("bg_asymm_3");
headerCols.add("bg_asymm_4");
}
if (otherMotifs != null) {
for (int m = 0; m < otherMotifs.length; m++) {
headerCols.add("besthit_" + otherMotifs[m].getName() + "(" + otherMotifToFileMap.get(otherMotifs[m].getName()) + ")");
}
}
if (metamotifs != null) {
if (calcAvgMetaMotifScore == false && calcMaxMetaMotifScore == false) {
System.err.println("");
System.exit(1);
}
if (calcAvgMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitavg_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
if (calcMaxMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitmax_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
}
if (printHeader) {
//first cap the header column lengths (so R doesn't complain...)
for (int i = 0; i < headerCols.size(); i++) {
String str = headerCols.get(i);
if (str.length() >= maxHeaderColWidth) {
str = str.substring(0,maxHeaderColWidth);
headerCols.set(i, str);
}
}
for (int i = 0; i < headerCols.size(); i++) {
if (i < (headerCols.size() - 1))
System.out.print(headerCols.get(i) + separator);
else
System.out.print(headerCols.get(i) + "\n");
}
}
for (int m = 0; m < motifs.length; m++) {
Motif mot = motifs[m];
boolean somethingPrinted = false;
if (showName) {
System.out.print(mot.getName());
somethingPrinted = true;
}
if (length) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allLengths[m] + separator);
somethingPrinted = true;
}
if (perMotifAvgEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allEntropies[m]);
somethingPrinted = true;
}
if (perMotifTotalEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allTotalEntropies[m]);
somethingPrinted = true;
}
if (palindromicity) {
if (somethingPrinted) System.out.print(separator);
System.out.print(gappedPalindromicities1[m] + separator);
System.out.print(gappedPalindromicities2[m] + separator);
System.out.print(gappedPalindromicities3[m] + separator);
System.out.print(selfRepeatednesses[m] + separator);
somethingPrinted = true;
}
if (bg) {
if (somethingPrinted) System.out.print(separator);
System.out.println(symmBGParams[m] + separator);
for (int i = 0; i < alphab.size(); i++) {
if (i < (alphab.size()-1)) {
System.out.print(asymmBGParams[m][i] + separator);
} else {
System.out.print(asymmBGParams[m][i]);
}
}
somethingPrinted = true;
}
if (otherMotifs != null &! pairedOutput) {
if (somethingPrinted) System.out.print(separator);
for (int n = 0; n < otherMotifs.length; n++) {
System.err.printf("m:%d n:%d obj:%s%n",m,n,otherMotifBestHits.toString());
if (n < (otherMotifs.length-1)) {
System.out.print(otherMotifBestHits[m][n] + separator);
} else {
System.out.print(otherMotifBestHits[m][n]);
}
}
somethingPrinted = true;
}
if (metamotifs != null) {
if (somethingPrinted) System.out.print(separator);
for (int mm = 0; mm < metamotifs.length; mm++) {
if (calcAvgMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifAvgHits[m][mm] + separator);
else
System.out.print(metaMotifAvgHits[m][mm]);
}
if (calcMaxMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifBestHits[m][mm] + separator);
else
System.out.print(metaMotifBestHits[m][mm]);
}
}
somethingPrinted = true;
}
System.out.println();
}
}
| public void main(String[] args) throws Exception {
if (calcAll) {
length = true;
perMotifAvgEntropy = true;
perMotifTotalEntropy = true;
gcContent = true;
palindromicity = true;
bg = true;
}
if (indices != null) {
Motif[] selMotifs = new Motif[indices.length];
for (int i = 0; i < indices.length; i++) {
selMotifs[i] = motifs[indices[i]];
}
motifs = selMotifs;
}
if (merged && (motifs.length > 1)) {
MotifAlignment alignment = new MotifAlignment(motifs, mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = new MotifAlignment(alignment.motifs(), mc);
alignment = alignment.alignmentWithZeroOffset();
if (outputAlignedFile != null) {
MotifIOTools.writeMotifSetXML(
new BufferedOutputStream(new FileOutputStream(outputAlignedFile)),
new Motif[] {alignment.averageMotif()});
}
try {
alignment = alignment.trimToColumnsPerPosition(minColPerPos);
} catch (NoPositionFoundException e) {
System.err.printf(
"WARNING! No position was found with at least %d columns. " +
"Will output the alignment without trimming.", minColPerPos);
}
motifs = new Motif[] {alignment.averageMotif()};
}
if (pseudoCount > 0) {
for (Motif m : motifs)
MotifTools.addPseudoCounts(m,pseudoCount);
if (otherMotifs != null)
for (Motif m : otherMotifs)
MotifTools.addPseudoCounts(m, pseudoCount);
} if (pseudoCount < 0) {
System.out.println(
"ERROR: -pseudoCount = " +
pseudoCount +
" + (nonnegative value required)");
System.exit(1);
}
if (maxAlphaSum > 0 && metamotifs != null) {
for (MetaMotif m : metamotifs) {
for (int i = 0; i < m.columns(); i++) {
Dirichlet dd = m.getColumn(i);
if (dd.alphaSum() > maxAlphaSum) {
dd.scaleAlphaSum(maxAlphaSum / dd.alphaSum());
}
}
}
}
if (perColEntropy) {
Distribution[] allDists = allDists();
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
System.out.println(entropyElsewhere);
for (Motif m : motifs)
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
System.out.println(m.getName() + separator +
i + separator +
(entropyElsewhere -
DistributionTools.totalEntropy(
m.getWeightMatrix().getColumn(i))));
}
System.exit(0);
}
if (perColAvgEntropy) {
Distribution[] allDists = allDists();
double[] entropies = new double[allDists.length];
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
double entropyElsewhere = DistributionTools.totalEntropy(elsewhere);
for (int i = 0; i < entropies.length; i++)
entropies[i] = entropyElsewhere - DistributionTools.totalEntropy(allDists[i]);
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(entropies));
System.out.println(bin.mean());
System.exit(0);
}
double[] allEntropies = new double[this.motifs.length];
double[] allLengths = new double[this.motifs.length];
double[] allTotalEntropies = new double[this.motifs.length];
if (perMotifAvgEntropy ||
perMotifTotalEntropy) {
int mI = 0;
Distribution elsewhere = new UniformDistribution((FiniteAlphabet)motifs[0].getWeightMatrix().getAlphabet());
for (Motif m : this.motifs) {
allTotalEntropies[mI] = MotifSetSummary.weightMatrixTotalEntropy(m.getWeightMatrix(), elsewhere);
allEntropies[mI++] = MotifSetSummary.weightMatrixAverageColumnEntropy(m.getWeightMatrix(), elsewhere);
}
}
if (length) {
int mI = 0;
for (Motif m : this.motifs) {
allLengths[mI++] = m.getWeightMatrix().columns();
}
}
double[][] metaMotifBestHits = new double[this.motifs.length][];
double[][] metaMotifAvgHits = new double[this.motifs.length][];
double[][] otherMotifBestHits = new double[this.motifs.length][];
List<String> headerCols = new ArrayList<String>();
if (bestHits || bestReciprocalHits) {
if (bestHits && bestReciprocalHits) {
System.err.println("-bestHits and -bestReciprocalHits are exclusive");
System.exit(1);
}
}
if (bestHits) {
if (otherMotifs != null) {
//paired output cannot be combined with calculating other motifs.
if (pairedOutput) {
MotifPair[] mpairs = SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHits(motifs, otherMotifs);
if (printHeader) {
System.out.println("motif1" + separator + "motif2" + separator + "score");
}
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
//not paired output with other motifs = table of distances with each column being one of the 'other' motifs
else {
System.err.println("Not paired output");
Matrix2D motifDistances =
SquaredDifferenceMotifComparitor
.getMotifComparitor().bestHitsMatrix(motifs, otherMotifs);
System.err.printf("rows: %d cols: %d%n", motifDistances.rows(), motifDistances.columns());
for (int i = 0; i < motifDistances.rows(); i++) {
System.err.printf("Row: %d columns: %d%n", i, motifDistances.columns());
otherMotifBestHits[i] = new double[motifDistances.columns()];
for (int j = 0; j < motifDistances.columns(); j++) {
double d = motifDistances.get(i, j);
otherMotifBestHits[i][j] = d;
}
}
}
}
//print the distance matrix of motifs against themselves
//again, a separate output mode from all the rest,
//cannot be combined with calculating other features
else {
printSelfSimilaryMatrix(motifs, separator);
//exit because can't be combine with other output forms
System.exit(0);
}
}
if (bestReciprocalHits) {
MotifPair[] mpairs =
SquaredDifferenceMotifComparitor
.getMotifComparitor()
.bestReciprocalHits(motifs, otherMotifs);
for (MotifPair mp : mpairs) {
System.out.print(mp.getM1().getName() + separator);
System.out.print(mp.getM2().getName() + separator);
System.out.print(mp.getScore() + "\n");
}
//exit because can't be combine with other output forms
System.exit(0);
}
/*
* Why not score them with the 1D dynamic programming based tiling of metamotifs that
* you can actually fit in that motif?
*/
if (metamotifs != null) {
for (int i = 0; i < motifs.length; i++) {
Motif m = motifs[i];
metaMotifBestHits[i] = new double[metamotifs.length];
metaMotifAvgHits[i] = new double[metamotifs.length];
for (int j = 0; j < metamotifs.length; j++) {
MetaMotif mm = metamotifs[j];
double[] probs = null;
if (mm.columns() <= m.getWeightMatrix().columns())
probs = mm.logProbDensities(m.getWeightMatrix());
if (probs != null) {
StaticBin1D bin = new StaticBin1D();
for (double d : probs)
if (!Double.isInfinite(d) && !Double.isNaN(d))
bin.add(d);
if (bin.size() > 0) {
metaMotifAvgHits[i][j] = bin.mean();
metaMotifBestHits[i][j] = bin.max();
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
} else {
metaMotifAvgHits[i][j] = VERY_NEGATIVE_DOUBLE;
metaMotifBestHits[i][j] = VERY_NEGATIVE_DOUBLE;
}
}
}
}
double[] palindromicities = new double[motifs.length];
double[] gappedPalindromicities1 = new double[motifs.length];
double[] gappedPalindromicities2 = new double[motifs.length];
double[] gappedPalindromicities3 = new double[motifs.length];
double[] selfRepeatednesses = new double[motifs.length];
if (palindromicity) {
for (int m = 0; m < palindromicities.length; m++) {
palindromicities[m] = howPalindromic(motifs[m]);
gappedPalindromicities1[m] = howGappedPalindromic(motifs[m], 1);
gappedPalindromicities2[m] = howGappedPalindromic(motifs[m], 2);
gappedPalindromicities3[m] = howGappedPalindromic(motifs[m], 3);
selfRepeatednesses[m] = howSelfRepeating(motifs[m]);
}
}
double[] gcContents = new double[this.motifs.length];
if (gcContent) {
for (int m = 0; m < this.motifs.length; m++) {
double gc = 0;
double total = 0;
for (int i = 0, cols = motifs[m].getWeightMatrix().columns(); i < cols; i++) {
Distribution distrib = motifs[m].getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
if (sym.equals(DNATools.g()) || sym.equals(DNATools.c())){
gc = gc + distrib.getWeight(sym);
}
total = distrib.getWeight(sym);
}
}
gcContents[m] = gc / total;
}
}
if (avgLength) {
double[] lengths = new double[motifs.length];
for (int i = 0; i < lengths.length; i++)
lengths[i] = motifs[i].getWeightMatrix().columns();
StaticBin1D bin = new StaticBin1D();
bin.addAllOf(new DoubleArrayList(lengths));
System.out.println(bin.mean());
System.exit(0);
}
if (num) {
System.out.println(motifs.length);
System.exit(0);
}
double avgDiff = 0.0;
FiniteAlphabet alphab = (FiniteAlphabet) this.motifs[0].getWeightMatrix().getAlphabet();
double[] symmBGParams = new double[motifs.length];
double[][] asymmBGParams = new double[motifs.length][alphab.size()];
AlphabetIndex alphabIndex = AlphabetManager.getAlphabetIndex(alphab);
if (bg) {
for (int m = 0; m < motifs.length; m++) {
Distribution[] ds = new Distribution[motifs[m].getWeightMatrix().columns()];
for (int i = 0; i < ds.length; i++) {
ds[i] = motifs[m].getWeightMatrix().getColumn(i);
}
Dirichlet dd;
try {
dd = DirichletParamEstimator.mle(ds,0.01);
} catch (IllegalAlphaParameterException e) {
System.err.printf(
"Could not estimate background for motif %s", motifs[m].getName());
dd = new Dirichlet((FiniteAlphabet)motifs[m].getWeightMatrix().getAlphabet());
}
Dirichlet symmDD = MetaMotifBackgroundParameterEstimator
.symmetricDirichlet(ds, 0.1, 10, 0.01);
for (int i = 0; i < asymmBGParams[m].length; i++) {
asymmBGParams[m][i] = dd.getWeight(alphabIndex.symbolForIndex(i));
}
//Symmetric, all weights the same --> let's just take the first one
symmBGParams[m] = symmDD.getWeight(alphabIndex.symbolForIndex(0));
}
}
if (showName) headerCols.add("name");
if (length) headerCols.add("length");
if (perMotifAvgEntropy) headerCols.add("avg-entropy");
if (perMotifTotalEntropy) headerCols.add("total-entropy");
if (palindromicity) {
headerCols.add("pal0");
headerCols.add("pal1");
headerCols.add("pal2");
headerCols.add("pal3");
headerCols.add("selfrep");
}
if (bg) {
headerCols.add("bgsymm");
headerCols.add("bg_asymm_1");
headerCols.add("bg_asymm_2");
headerCols.add("bg_asymm_3");
headerCols.add("bg_asymm_4");
}
if (otherMotifs != null) {
for (int m = 0; m < otherMotifs.length; m++) {
headerCols.add("besthit_" + otherMotifs[m].getName() + "(" + otherMotifToFileMap.get(otherMotifs[m].getName()) + ")");
}
}
if (metamotifs != null) {
if (calcAvgMetaMotifScore == false && calcMaxMetaMotifScore == false) {
System.err.println("");
System.exit(1);
}
if (calcAvgMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitavg_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
if (calcMaxMetaMotifScore) {
for (int mm = 0; mm < metamotifs.length; mm++) {
headerCols.add("hitmax_" + metamotifs[mm].getName() +
"("+metaMotifToFileMap.get(metamotifs[mm]).getName()+")");
}
}
}
if (printHeader) {
//first cap the header column lengths (so R doesn't complain...)
for (int i = 0; i < headerCols.size(); i++) {
String str = headerCols.get(i);
if (str.length() >= maxHeaderColWidth) {
str = str.substring(0,maxHeaderColWidth);
headerCols.set(i, str);
}
}
for (int i = 0; i < headerCols.size(); i++) {
if (i < (headerCols.size() - 1))
System.out.print(headerCols.get(i) + separator);
else
System.out.print(headerCols.get(i) + "\n");
}
}
for (int m = 0; m < motifs.length; m++) {
Motif mot = motifs[m];
boolean somethingPrinted = false;
if (showName) {
System.out.print(mot.getName());
somethingPrinted = true;
}
if (length) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allLengths[m] + separator);
somethingPrinted = true;
}
if (perMotifAvgEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allEntropies[m]);
somethingPrinted = true;
}
if (perMotifTotalEntropy) {
if (somethingPrinted) System.out.print(separator);
System.out.print(allTotalEntropies[m]);
somethingPrinted = true;
}
if (palindromicity) {
if (somethingPrinted) System.out.print(separator);
System.out.print(gappedPalindromicities1[m] + separator);
System.out.print(gappedPalindromicities2[m] + separator);
System.out.print(gappedPalindromicities3[m] + separator);
System.out.print(selfRepeatednesses[m] + separator);
somethingPrinted = true;
}
if (bg) {
if (somethingPrinted) System.out.print(separator);
System.out.print(symmBGParams[m] + separator);
for (int i = 0; i < alphab.size(); i++) {
if (i < (alphab.size()-1)) {
System.out.print(asymmBGParams[m][i] + separator);
} else {
System.out.print(asymmBGParams[m][i]);
}
}
somethingPrinted = true;
}
if (otherMotifs != null &! pairedOutput) {
if (somethingPrinted) System.out.print(separator);
for (int n = 0; n < otherMotifs.length; n++) {
System.err.printf("m:%d n:%d obj:%s%n",m,n,otherMotifBestHits.toString());
if (n < (otherMotifs.length-1)) {
System.out.print(otherMotifBestHits[m][n] + separator);
} else {
System.out.print(otherMotifBestHits[m][n]);
}
}
somethingPrinted = true;
}
if (metamotifs != null) {
if (somethingPrinted) System.out.print(separator);
for (int mm = 0; mm < metamotifs.length; mm++) {
if (calcAvgMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifAvgHits[m][mm] + separator);
else
System.out.print(metaMotifAvgHits[m][mm]);
}
if (calcMaxMetaMotifScore) {
if (mm < (metamotifs.length-1))
System.out.print(metaMotifBestHits[m][mm] + separator);
else
System.out.print(metaMotifBestHits[m][mm]);
}
}
somethingPrinted = true;
}
System.out.println();
}
}
|
diff --git a/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java b/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java
index 49b7501ad5..abf4b3502c 100644
--- a/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java
+++ b/server/src/main/java/io/druid/segment/loading/S3DataSegmentPuller.java
@@ -1,212 +1,221 @@
/*
* Druid - a distributed column store.
* Copyright (C) 2012, 2013 Metamarkets Group 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.druid.segment.loading;
import com.google.common.base.Throwables;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.metamx.common.ISE;
import com.metamx.common.MapUtils;
import com.metamx.common.logger.Logger;
import io.druid.common.utils.CompressionUtils;
import io.druid.storage.s3.S3Utils;
import io.druid.timeline.DataSegment;
import org.apache.commons.io.FileUtils;
import org.jets3t.service.ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.zip.GZIPInputStream;
/**
*/
public class S3DataSegmentPuller implements DataSegmentPuller
{
private static final Logger log = new Logger(S3DataSegmentPuller.class);
private static final String BUCKET = "bucket";
private static final String KEY = "key";
private final RestS3Service s3Client;
@Inject
public S3DataSegmentPuller(
RestS3Service s3Client
)
{
this.s3Client = s3Client;
}
@Override
public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException
{
final S3Coords s3Coords = new S3Coords(segment);
log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir);
if (!isObjectInBucket(s3Coords)) {
throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords);
}
if (!outDir.exists()) {
outDir.mkdirs();
}
if (!outDir.isDirectory()) {
throw new ISE("outDir[%s] must be a directory.", outDir);
}
try {
S3Utils.retryS3Operation(
new Callable<Void>()
{
@Override
public Void call() throws Exception
{
long startTime = System.currentTimeMillis();
S3Object s3Obj = null;
try {
s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path);
InputStream in = null;
try {
in = s3Obj.getDataInputStream();
final String key = s3Obj.getKey();
if (key.endsWith(".zip")) {
CompressionUtils.unzip(in, outDir);
} else if (key.endsWith(".gz")) {
final File outFile = new File(outDir, toFilename(key, ".gz"));
ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile));
} else {
ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, ""))));
}
log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime);
return null;
}
catch (IOException e) {
- FileUtils.deleteDirectory(outDir);
throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e);
}
finally {
Closeables.closeQuietly(in);
}
}
finally {
S3Utils.closeStreamsQuietly(s3Obj);
}
}
}
);
}
catch (Exception e) {
+ try {
+ FileUtils.deleteDirectory(outDir);
+ } catch (IOException ioe) {
+ log.warn(
+ ioe,
+ "Failed to remove output directory for segment[%s] after exception: %s",
+ segment.getIdentifier(),
+ outDir
+ );
+ }
throw new SegmentLoadingException(e, e.getMessage());
}
}
private String toFilename(String key, final String suffix)
{
String filename = key.substring(key.lastIndexOf("/") + 1); // characters after last '/'
filename = filename.substring(0, filename.length() - suffix.length()); // remove the suffix from the end
return filename;
}
private boolean isObjectInBucket(final S3Coords coords) throws SegmentLoadingException
{
try {
return S3Utils.retryS3Operation(
new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return s3Client.isObjectInBucket(coords.bucket, coords.path);
}
}
);
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
catch (IOException e) {
throw new SegmentLoadingException(e, "S3 fail! Key[%s]", coords);
}
catch (ServiceException e) {
throw new SegmentLoadingException(e, "S3 fail! Key[%s]", coords);
}
}
@Override
public long getLastModified(DataSegment segment) throws SegmentLoadingException
{
final S3Coords coords = new S3Coords(segment);
try {
final StorageObject objDetails = S3Utils.retryS3Operation(
new Callable<StorageObject>()
{
@Override
public StorageObject call() throws Exception
{
return s3Client.getObjectDetails(coords.bucket, coords.path);
}
}
);
return objDetails.getLastModifiedDate().getTime();
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
catch (IOException e) {
throw new SegmentLoadingException(e, e.getMessage());
}
catch (ServiceException e) {
throw new SegmentLoadingException(e, e.getMessage());
}
}
private static class S3Coords
{
String bucket;
String path;
public S3Coords(DataSegment segment)
{
Map<String, Object> loadSpec = segment.getLoadSpec();
bucket = MapUtils.getString(loadSpec, BUCKET);
path = MapUtils.getString(loadSpec, KEY);
if (path.startsWith("/")) {
path = path.substring(1);
}
}
public String toString()
{
return String.format("s3://%s/%s", bucket, path);
}
}
}
| false | true | public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException
{
final S3Coords s3Coords = new S3Coords(segment);
log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir);
if (!isObjectInBucket(s3Coords)) {
throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords);
}
if (!outDir.exists()) {
outDir.mkdirs();
}
if (!outDir.isDirectory()) {
throw new ISE("outDir[%s] must be a directory.", outDir);
}
try {
S3Utils.retryS3Operation(
new Callable<Void>()
{
@Override
public Void call() throws Exception
{
long startTime = System.currentTimeMillis();
S3Object s3Obj = null;
try {
s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path);
InputStream in = null;
try {
in = s3Obj.getDataInputStream();
final String key = s3Obj.getKey();
if (key.endsWith(".zip")) {
CompressionUtils.unzip(in, outDir);
} else if (key.endsWith(".gz")) {
final File outFile = new File(outDir, toFilename(key, ".gz"));
ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile));
} else {
ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, ""))));
}
log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime);
return null;
}
catch (IOException e) {
FileUtils.deleteDirectory(outDir);
throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e);
}
finally {
Closeables.closeQuietly(in);
}
}
finally {
S3Utils.closeStreamsQuietly(s3Obj);
}
}
}
);
}
catch (Exception e) {
throw new SegmentLoadingException(e, e.getMessage());
}
}
| public void getSegmentFiles(final DataSegment segment, final File outDir) throws SegmentLoadingException
{
final S3Coords s3Coords = new S3Coords(segment);
log.info("Pulling index at path[%s] to outDir[%s]", s3Coords, outDir);
if (!isObjectInBucket(s3Coords)) {
throw new SegmentLoadingException("IndexFile[%s] does not exist.", s3Coords);
}
if (!outDir.exists()) {
outDir.mkdirs();
}
if (!outDir.isDirectory()) {
throw new ISE("outDir[%s] must be a directory.", outDir);
}
try {
S3Utils.retryS3Operation(
new Callable<Void>()
{
@Override
public Void call() throws Exception
{
long startTime = System.currentTimeMillis();
S3Object s3Obj = null;
try {
s3Obj = s3Client.getObject(s3Coords.bucket, s3Coords.path);
InputStream in = null;
try {
in = s3Obj.getDataInputStream();
final String key = s3Obj.getKey();
if (key.endsWith(".zip")) {
CompressionUtils.unzip(in, outDir);
} else if (key.endsWith(".gz")) {
final File outFile = new File(outDir, toFilename(key, ".gz"));
ByteStreams.copy(new GZIPInputStream(in), Files.newOutputStreamSupplier(outFile));
} else {
ByteStreams.copy(in, Files.newOutputStreamSupplier(new File(outDir, toFilename(key, ""))));
}
log.info("Pull of file[%s] completed in %,d millis", s3Obj, System.currentTimeMillis() - startTime);
return null;
}
catch (IOException e) {
throw new IOException(String.format("Problem decompressing object[%s]", s3Obj), e);
}
finally {
Closeables.closeQuietly(in);
}
}
finally {
S3Utils.closeStreamsQuietly(s3Obj);
}
}
}
);
}
catch (Exception e) {
try {
FileUtils.deleteDirectory(outDir);
} catch (IOException ioe) {
log.warn(
ioe,
"Failed to remove output directory for segment[%s] after exception: %s",
segment.getIdentifier(),
outDir
);
}
throw new SegmentLoadingException(e, e.getMessage());
}
}
|
diff --git a/src/Executor.java b/src/Executor.java
index 47e5866..bf02c8b 100644
--- a/src/Executor.java
+++ b/src/Executor.java
@@ -1,73 +1,77 @@
import java.io.OutputStream;
/**
* @author E. Javier Figueroa
* COP5615 Spring 2011
* University of Florida
*
*/
public class Executor implements Runnable {
private String host;
private String server;
private int port;
private int id;
private Action type;
private long sleep;
public int getId() {
return id;
}
public Executor(String host, String server, int port, int id, Action type, long sleep) {
this.host = host;
this.server = server;
this.port = port;
this.id = id;
this.type = type;
this.sleep = sleep;
}
public void run() {
String path = System.getProperty("user.dir");
Log.write("Starting Remote Process: Client ID: " + this.id + " on "
+ this.host);
int times = Integer.parseInt(PropertyManager.getProperties().get("RW.numberOfAccesses"));
String[] command = {
"ssh",
+ "-o",
+ "UserKnownHostsFile=/dev/null",
+ "-o",
+ "StrictHostKeyChecking=no",
"-i",
"id_rsa",
"figueroa@" + this.host,
- "~/.ssh/id_rsa",
+ "id_rsa",
// "javier.figueroa@" + this.host,
"cd " + path + " ; java start "
// "cd " + path + " ; java -jar start.jar "
+ this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep };
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
Log.write("Status: SUCCESS! Parameters Passed: " + this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep) ;
OutputStream stdin = pr.getOutputStream();
String carriageReturn = "\n";
stdin.write(carriageReturn.getBytes());
stdin.flush();
stdin.close();
pr.waitFor();
int exitValue = pr.exitValue();
if (exitValue != 0) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
}
} catch (Exception e) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
e.printStackTrace();
}
}
}
| false | true | public void run() {
String path = System.getProperty("user.dir");
Log.write("Starting Remote Process: Client ID: " + this.id + " on "
+ this.host);
int times = Integer.parseInt(PropertyManager.getProperties().get("RW.numberOfAccesses"));
String[] command = {
"ssh",
"-i",
"id_rsa",
"figueroa@" + this.host,
"~/.ssh/id_rsa",
// "javier.figueroa@" + this.host,
"cd " + path + " ; java start "
// "cd " + path + " ; java -jar start.jar "
+ this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep };
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
Log.write("Status: SUCCESS! Parameters Passed: " + this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep) ;
OutputStream stdin = pr.getOutputStream();
String carriageReturn = "\n";
stdin.write(carriageReturn.getBytes());
stdin.flush();
stdin.close();
pr.waitFor();
int exitValue = pr.exitValue();
if (exitValue != 0) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
}
} catch (Exception e) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
e.printStackTrace();
}
}
| public void run() {
String path = System.getProperty("user.dir");
Log.write("Starting Remote Process: Client ID: " + this.id + " on "
+ this.host);
int times = Integer.parseInt(PropertyManager.getProperties().get("RW.numberOfAccesses"));
String[] command = {
"ssh",
"-o",
"UserKnownHostsFile=/dev/null",
"-o",
"StrictHostKeyChecking=no",
"-i",
"id_rsa",
"figueroa@" + this.host,
"id_rsa",
// "javier.figueroa@" + this.host,
"cd " + path + " ; java start "
// "cd " + path + " ; java -jar start.jar "
+ this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep };
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
Log.write("Status: SUCCESS! Parameters Passed: " + this.server + " " + this.port + " " + this.id + " " + type.name() + " " + times + " " + sleep) ;
OutputStream stdin = pr.getOutputStream();
String carriageReturn = "\n";
stdin.write(carriageReturn.getBytes());
stdin.flush();
stdin.close();
pr.waitFor();
int exitValue = pr.exitValue();
if (exitValue != 0) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
}
} catch (Exception e) {
Log.write("Warning: Remote Process could not start for " + this.type + " Client ID: " + this.id + ", host: " + this.host);
// Server.workers--;
e.printStackTrace();
}
}
|
diff --git a/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/CertificateClasses/CertificateCSRR.java b/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/CertificateClasses/CertificateCSRR.java
index 24a6301..d6bd157 100644
--- a/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/CertificateClasses/CertificateCSRR.java
+++ b/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/CertificateClasses/CertificateCSRR.java
@@ -1,121 +1,134 @@
package org.jcryptool.visual.jctca.CertificateClasses;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.jcryptool.visual.jctca.Util;
public class CertificateCSRR {
private static CertificateCSRR instance = null;
private ArrayList<CSR> approved_csrs;
private ArrayList<RR> revocations;
private ArrayList<AsymmetricCipherKeyPair> caKeys;
private ArrayList<X509Certificate> certs;
private CertificateCSRR(){
approved_csrs = new ArrayList<CSR>();
revocations = new ArrayList<RR>();
caKeys = new ArrayList<AsymmetricCipherKeyPair>();
certs = new ArrayList<X509Certificate>();
// GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
SecureRandom sr = new SecureRandom();
gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3),
sr, 1024, 80));
Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);// time from which certificate is valid
Date expiryDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);// time after which certificate is not valid
BigInteger serialNumber = new BigInteger(System.currentTimeMillis()+"");// serial number for certificate
AsymmetricCipherKeyPair keypair =null;
for(int i = 0; i<5; i++){
keypair= gen.generateKeyPair();
KeyPair kp = Util.asymmetricKeyPairToNormalKeyPair(keypair);
// yesterday
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
// in 2 years
Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X509Name dnName = new X509Name("CN=JCrypTool, O=JCrypTool, OU=JCT-CA Visual");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(dnName); // use the same
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(kp.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = null;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cert = certGen.generate(kp.getPrivate(), "BC");
- } catch (CertificateEncodingException | InvalidKeyException
- | IllegalStateException | NoSuchProviderException
- | NoSuchAlgorithmException | SignatureException e) {
+ } catch (CertificateEncodingException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (InvalidKeyException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IllegalStateException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (NoSuchProviderException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (NoSuchAlgorithmException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
caKeys.add(keypair);
certs.add(cert);
}
}
public static CertificateCSRR getInstance(){
if(instance==null){
instance = new CertificateCSRR();
}
return instance;
}
public void addCSR(CSR c){
approved_csrs.add(c);
}
public ArrayList<CSR> getApproved(){
return approved_csrs;
}
public AsymmetricCipherKeyPair getCAKey(int i){
return caKeys.get(i);
}
public X509Certificate getCACert(int i){
return certs.get(i);
}
public ArrayList<RR> getRevocations(){
return revocations;
}
public ArrayList<AsymmetricCipherKeyPair> getCAKeys() {
return caKeys;
}
public void removeCSR(int i){
this.approved_csrs.remove(i);
}
public void removeCSR(CSR c){
this.approved_csrs.remove(c);
}
public void removeRR(RR r){
this.revocations.remove(r);
}
}
| true | true | private CertificateCSRR(){
approved_csrs = new ArrayList<CSR>();
revocations = new ArrayList<RR>();
caKeys = new ArrayList<AsymmetricCipherKeyPair>();
certs = new ArrayList<X509Certificate>();
// GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
SecureRandom sr = new SecureRandom();
gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3),
sr, 1024, 80));
Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);// time from which certificate is valid
Date expiryDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);// time after which certificate is not valid
BigInteger serialNumber = new BigInteger(System.currentTimeMillis()+"");// serial number for certificate
AsymmetricCipherKeyPair keypair =null;
for(int i = 0; i<5; i++){
keypair= gen.generateKeyPair();
KeyPair kp = Util.asymmetricKeyPairToNormalKeyPair(keypair);
// yesterday
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
// in 2 years
Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X509Name dnName = new X509Name("CN=JCrypTool, O=JCrypTool, OU=JCT-CA Visual");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(dnName); // use the same
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(kp.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = null;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cert = certGen.generate(kp.getPrivate(), "BC");
} catch (CertificateEncodingException | InvalidKeyException
| IllegalStateException | NoSuchProviderException
| NoSuchAlgorithmException | SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
caKeys.add(keypair);
certs.add(cert);
}
}
| private CertificateCSRR(){
approved_csrs = new ArrayList<CSR>();
revocations = new ArrayList<RR>();
caKeys = new ArrayList<AsymmetricCipherKeyPair>();
certs = new ArrayList<X509Certificate>();
// GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
SecureRandom sr = new SecureRandom();
gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3),
sr, 1024, 80));
Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);// time from which certificate is valid
Date expiryDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);// time after which certificate is not valid
BigInteger serialNumber = new BigInteger(System.currentTimeMillis()+"");// serial number for certificate
AsymmetricCipherKeyPair keypair =null;
for(int i = 0; i<5; i++){
keypair= gen.generateKeyPair();
KeyPair kp = Util.asymmetricKeyPairToNormalKeyPair(keypair);
// yesterday
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
// in 2 years
Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X509Name dnName = new X509Name("CN=JCrypTool, O=JCrypTool, OU=JCT-CA Visual");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(dnName); // use the same
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(kp.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = null;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cert = certGen.generate(kp.getPrivate(), "BC");
} catch (CertificateEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
caKeys.add(keypair);
certs.add(cert);
}
}
|
diff --git a/src/biz/bokhorst/xprivacy/XApplication.java b/src/biz/bokhorst/xprivacy/XApplication.java
index 4d8776b4..91db3760 100644
--- a/src/biz/bokhorst/xprivacy/XApplication.java
+++ b/src/biz/bokhorst/xprivacy/XApplication.java
@@ -1,171 +1,172 @@
package biz.bokhorst.xprivacy;
import java.util.ArrayList;
import java.util.List;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Process;
import android.util.Log;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
public class XApplication extends XHook {
private Methods mMethod;
private static boolean mReceiverInstalled = false;
public static String cAction = "Action";
public static String cActionKillProcess = "Kill";
public static String cActionFlushCache = "Flush";
public static String ACTION_MANAGE_PACKAGE = "biz.bokhorst.xprivacy.ACTION_MANAGE_PACKAGE";
public static String PERMISSION_MANAGE_PACKAGES = "biz.bokhorst.xprivacy.MANAGE_PACKAGES";
public XApplication(Methods method, String restrictionName, String actionName) {
super(restrictionName, method.name(), actionName);
mMethod = method;
}
@Override
public String getClassName() {
return "android.app.Application";
}
// public void onCreate()
// frameworks/base/core/java/android/app/Application.java
// http://developer.android.com/reference/android/app/Application.html
private enum Methods {
onCreate
};
public static List<XHook> getInstances() {
List<XHook> listHook = new ArrayList<XHook>();
listHook.add(new XApplication(Methods.onCreate, null, null));
return listHook;
}
@Override
protected void before(MethodHookParam param) throws Throwable {
// do nothing
}
@Override
protected void after(MethodHookParam param) throws Throwable {
if (mMethod == Methods.onCreate) {
Application app = (Application) param.thisObject;
// Install uncaught exception handler
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(defaultHandler instanceof XUncaughtExceptionHandler)) {
Util.log(this, Log.INFO, "Installing XUncaughtExceptionHandler uid=" + Process.myUid());
Thread.setDefaultUncaughtExceptionHandler(new XUncaughtExceptionHandler(this, app, defaultHandler));
}
// Install receiver for package management
- if (Util.getAppId(Process.myUid()) != PrivacyManager.cAndroidUid) {
+ int uid = Process.myUid();
+ if (Util.getAppId(uid) != PrivacyManager.cAndroidUid && !PrivacyManager.isIsolated(uid)) {
boolean experimental = PrivacyManager.getSettingBool(null, null, 0,
PrivacyManager.cSettingExperimental, PrivacyManager.cTestVersion, true);
if (experimental && !mReceiverInstalled)
try {
mReceiverInstalled = true;
Util.log(this, Log.INFO, "Installing receiver uid=" + Process.myUid());
app.registerReceiver(new Receiver(app), new IntentFilter(ACTION_MANAGE_PACKAGE),
PERMISSION_MANAGE_PACKAGES, null);
} catch (Throwable ex) {
Util.bug(this, ex);
}
}
} else
Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
}
public static void manage(Context context, int uid, String action) {
if (uid == 0)
manage(context, null, action);
else {
String[] packageName = context.getPackageManager().getPackagesForUid(uid);
if (packageName != null && packageName.length > 0)
manage(context, packageName[0], action);
else
Util.log(null, Log.WARN, "No packages uid=" + uid + " action=" + action);
}
}
public static void manage(Context context, String packageName, String action) {
boolean experimental = PrivacyManager.getSettingBool(null, null, 0, PrivacyManager.cSettingExperimental,
PrivacyManager.cTestVersion, true);
if (experimental) {
Util.log(null, Log.INFO, "Manage package=" + packageName + " action=" + action);
if (packageName == null && XApplication.cActionKillProcess.equals(action)) {
Util.log(null, Log.WARN, "Kill all");
return;
}
Intent manageIntent = new Intent(XApplication.ACTION_MANAGE_PACKAGE);
manageIntent.putExtra(XApplication.cAction, action);
if (packageName != null)
manageIntent.setPackage(packageName);
context.sendBroadcast(manageIntent);
}
}
private class Receiver extends BroadcastReceiver {
private Application mApplication;
public Receiver(Application app) {
mApplication = app;
}
@Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getExtras().getString(cAction);
Util.log(null, Log.INFO, "Managing uid=" + Process.myUid() + " action=" + action);
if (cActionKillProcess.equals(action))
android.os.Process.killProcess(Process.myPid());
else if (cActionFlushCache.equals(action))
PrivacyManager.flush(mApplication, Process.myUid());
else
Util.log(null, Log.WARN, "Unknown management action=" + action);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
}
public static class XUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private XHook mHook;
private Context mContext;
private Thread.UncaughtExceptionHandler mDefaultHandler;
public XUncaughtExceptionHandler(XHook hook, Context context, Thread.UncaughtExceptionHandler defaultHandler) {
mHook = hook;
mContext = context;
mDefaultHandler = defaultHandler;
}
public Thread.UncaughtExceptionHandler getDefaultHandler() {
return mDefaultHandler;
}
public void setDefaultHandler(Thread.UncaughtExceptionHandler handler) {
Util.log(mHook, Log.INFO, "Setting new default handler uid=" + Process.myUid());
mDefaultHandler = handler;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
Util.log(mHook, Log.WARN, "Uncaught exception uid=" + Process.myUid() + ": " + ex);
PrivacyManager.sendUsageData(null, mContext);
} catch (Throwable exex) {
Util.bug(mHook, exex);
}
mDefaultHandler.uncaughtException(thread, ex);
}
}
}
| true | true | protected void after(MethodHookParam param) throws Throwable {
if (mMethod == Methods.onCreate) {
Application app = (Application) param.thisObject;
// Install uncaught exception handler
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(defaultHandler instanceof XUncaughtExceptionHandler)) {
Util.log(this, Log.INFO, "Installing XUncaughtExceptionHandler uid=" + Process.myUid());
Thread.setDefaultUncaughtExceptionHandler(new XUncaughtExceptionHandler(this, app, defaultHandler));
}
// Install receiver for package management
if (Util.getAppId(Process.myUid()) != PrivacyManager.cAndroidUid) {
boolean experimental = PrivacyManager.getSettingBool(null, null, 0,
PrivacyManager.cSettingExperimental, PrivacyManager.cTestVersion, true);
if (experimental && !mReceiverInstalled)
try {
mReceiverInstalled = true;
Util.log(this, Log.INFO, "Installing receiver uid=" + Process.myUid());
app.registerReceiver(new Receiver(app), new IntentFilter(ACTION_MANAGE_PACKAGE),
PERMISSION_MANAGE_PACKAGES, null);
} catch (Throwable 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.onCreate) {
Application app = (Application) param.thisObject;
// Install uncaught exception handler
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(defaultHandler instanceof XUncaughtExceptionHandler)) {
Util.log(this, Log.INFO, "Installing XUncaughtExceptionHandler uid=" + Process.myUid());
Thread.setDefaultUncaughtExceptionHandler(new XUncaughtExceptionHandler(this, app, defaultHandler));
}
// Install receiver for package management
int uid = Process.myUid();
if (Util.getAppId(uid) != PrivacyManager.cAndroidUid && !PrivacyManager.isIsolated(uid)) {
boolean experimental = PrivacyManager.getSettingBool(null, null, 0,
PrivacyManager.cSettingExperimental, PrivacyManager.cTestVersion, true);
if (experimental && !mReceiverInstalled)
try {
mReceiverInstalled = true;
Util.log(this, Log.INFO, "Installing receiver uid=" + Process.myUid());
app.registerReceiver(new Receiver(app), new IntentFilter(ACTION_MANAGE_PACKAGE),
PERMISSION_MANAGE_PACKAGES, null);
} catch (Throwable ex) {
Util.bug(this, ex);
}
}
} else
Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
}
|
diff --git a/login/src/main/java/org/soluvas/web/login/LogoutLink.java b/login/src/main/java/org/soluvas/web/login/LogoutLink.java
index ea6933fc..9378f7fc 100644
--- a/login/src/main/java/org/soluvas/web/login/LogoutLink.java
+++ b/login/src/main/java/org/soluvas/web/login/LogoutLink.java
@@ -1,38 +1,38 @@
package org.soluvas.web.login;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Logs the current user out and returns to "after logout page".
* @author ceefour
*/
@SuppressWarnings("serial")
public class LogoutLink extends AjaxLink<Void> {
private static final Logger log = LoggerFactory.getLogger(LogoutLink.class);
private final Component[] ajaxTargets;
public LogoutLink(String id, Component... ajaxTargets) {
super(id);
this.ajaxTargets = ajaxTargets;
}
@Override
public void onClick(AjaxRequestTarget target) {
Subject currentUser = SecurityUtils.getSubject();
final Class<? extends Page> homePage = getApplication().getHomePage();
log.info("Logging out {} and redirecting to {}", currentUser.getPrincipal(), homePage);
currentUser.logout();
info("Anda telah log out.");
- target.add(ajaxTargets);
-// getRequestCycle().setResponsePage(homePage);
+// target.add(ajaxTargets);
+ getRequestCycle().setResponsePage(homePage);
}
}
| true | true | public void onClick(AjaxRequestTarget target) {
Subject currentUser = SecurityUtils.getSubject();
final Class<? extends Page> homePage = getApplication().getHomePage();
log.info("Logging out {} and redirecting to {}", currentUser.getPrincipal(), homePage);
currentUser.logout();
info("Anda telah log out.");
target.add(ajaxTargets);
// getRequestCycle().setResponsePage(homePage);
}
| public void onClick(AjaxRequestTarget target) {
Subject currentUser = SecurityUtils.getSubject();
final Class<? extends Page> homePage = getApplication().getHomePage();
log.info("Logging out {} and redirecting to {}", currentUser.getPrincipal(), homePage);
currentUser.logout();
info("Anda telah log out.");
// target.add(ajaxTargets);
getRequestCycle().setResponsePage(homePage);
}
|
diff --git a/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java b/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java
index 3df85648..bf0aa311 100644
--- a/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java
+++ b/org.maven.ide.eclipse.tests/src/org/maven/ide/eclipse/tests/BuildPathManagerTest.java
@@ -1,1339 +1,1345 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.maven.ide.eclipse.tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IAccessRule;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.maven.ide.eclipse.MavenPlugin;
import org.maven.ide.eclipse.core.IMavenConstants;
import org.maven.ide.eclipse.index.IndexInfo;
import org.maven.ide.eclipse.index.IndexManager;
import org.maven.ide.eclipse.jdt.BuildPathManager;
import org.maven.ide.eclipse.jdt.MavenJdtPlugin;
import org.maven.ide.eclipse.project.IProjectConfigurationManager;
import org.maven.ide.eclipse.project.MavenUpdateRequest;
import org.maven.ide.eclipse.project.ProjectImportConfiguration;
import org.maven.ide.eclipse.project.ResolverConfiguration;
/**
* @author Eugene Kuleshov
*/
public class BuildPathManagerTest extends AsbtractMavenProjectTestCase {
public void testEnableMavenNature() throws Exception {
deleteProject("MNGECLIPSE-248parent");
deleteProject("MNGECLIPSE-248child");
final IProject project1 = createProject("MNGECLIPSE-248parent", "projects/MNGECLIPSE-248parent/pom.xml");
final IProject project2 = createProject("MNGECLIPSE-248child", "projects/MNGECLIPSE-248child/pom.xml");
NullProgressMonitor monitor = new NullProgressMonitor();
IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager();
ResolverConfiguration configuration = new ResolverConfiguration();
configurationManager.enableMavenNature(project1, configuration, monitor);
// buildpathManager.updateSourceFolders(project1, monitor);
configurationManager.enableMavenNature(project2, configuration, monitor);
// buildpathManager.updateSourceFolders(project2, monitor);
// waitForJob("Initializing " + project1.getProject().getName());
// waitForJob("Initializing " + project2.getProject().getName());
try {
project1.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
project2.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
} catch(Exception ex) {
throw ex;
}
waitForJobsToComplete();
IMarker[] markers1 = project1.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertTrue("Unexpected markers " + Arrays.asList(markers1), markers1.length == 0);
IClasspathEntry[] project1entries = getMavenContainerEntries(project1);
assertEquals(1, project1entries.length);
assertEquals(IClasspathEntry.CPE_LIBRARY, project1entries[0].getEntryKind());
assertEquals("junit-4.1.jar", project1entries[0].getPath().lastSegment());
IClasspathEntry[] project2entries = getMavenContainerEntries(project2);
assertEquals(2, project2entries.length);
assertEquals(IClasspathEntry.CPE_PROJECT, project2entries[0].getEntryKind());
assertEquals("MNGECLIPSE-248parent", project2entries[0].getPath().segment(0));
assertEquals(IClasspathEntry.CPE_LIBRARY, project2entries[1].getEntryKind());
assertEquals("junit-4.1.jar", project2entries[1].getPath().lastSegment());
}
public void testDisableMavenNature() throws Exception {
deleteProject("disablemaven-p001");
IProject p = createExisting("disablemaven-p001", "projects/disablemaven/p001");
waitForJobsToComplete();
assertTrue(p.hasNature(IMavenConstants.NATURE_ID));
assertTrue(p.hasNature(JavaCore.NATURE_ID));
assertNotNull(BuildPathManager.getMaven2ClasspathContainer(JavaCore.create(p)));
IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager();
configurationManager.disableMavenNature(p, monitor);
waitForJobsToComplete();
assertFalse(p.hasNature(IMavenConstants.NATURE_ID));
assertFalse(hasBuilder(p, IMavenConstants.BUILDER_ID));
assertTrue(p.hasNature(JavaCore.NATURE_ID));
assertNull(BuildPathManager.getMaven2ClasspathContainer(JavaCore.create(p)));
}
private boolean hasBuilder(IProject p, String builderId) throws CoreException {
for (ICommand command : p.getDescription().getBuildSpec()) {
if (builderId.equals(command.getBuilderName())) {
return true;
}
}
return false;
}
public void testEnableMavenNatureWithNoWorkspace() throws Exception {
deleteProject("MNGECLIPSE-248parent");
deleteProject("MNGECLIPSE-248child");
final IProject project1 = createProject("MNGECLIPSE-248parent", "projects/MNGECLIPSE-248parent/pom.xml");
final IProject project2 = createProject("MNGECLIPSE-248child", "projects/MNGECLIPSE-248child/pom.xml");
NullProgressMonitor monitor = new NullProgressMonitor();
IProjectConfigurationManager importManager = MavenPlugin.getDefault().getProjectConfigurationManager();
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
importManager.enableMavenNature(project1, configuration, monitor);
importManager.enableMavenNature(project2, configuration, monitor);
// buildpathManager.updateSourceFolders(project1, monitor);
// buildpathManager.updateSourceFolders(project2, monitor);
// waitForJob("Initializing " + project1.getProject().getName());
// waitForJob("Initializing " + project2.getProject().getName());
waitForJobsToComplete();
IClasspathEntry[] project1entries = getMavenContainerEntries(project1);
assertEquals(Arrays.asList(project1entries).toString(), 1, project1entries.length);
assertEquals(IClasspathEntry.CPE_LIBRARY, project1entries[0].getEntryKind());
assertEquals("junit-4.1.jar", project1entries[0].getPath().lastSegment());
IClasspathEntry[] project2entries = getMavenContainerEntries(project2);
assertEquals(Arrays.asList(project2entries).toString(), 1, project2entries.length);
assertEquals(IClasspathEntry.CPE_LIBRARY, project2entries[0].getEntryKind());
assertEquals("MNGECLIPSE-248parent-1.0.0.jar", project2entries[0].getPath().lastSegment());
}
public void testProjectImportDefault() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
IProject[] projects = importProjects("projects/MNGECLIPSE-20", new String[] {"pom.xml", "type/pom.xml",
"app/pom.xml", "web/pom.xml", "ejb/pom.xml", "ear/pom.xml",}, configuration);
waitForJobsToComplete();
{
IJavaProject javaProject = JavaCore.create(projects[0]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
IMarker[] markers = projects[0].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
IJavaProject javaProject = JavaCore.create(projects[1]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
IMarker[] markers = projects[1].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
IJavaProject javaProject = JavaCore.create(projects[2]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(3, classpathEntries.length);
assertEquals("MNGECLIPSE-20-type", classpathEntries[0].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[1].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[2].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-app/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
IMarker[] markers = projects[2].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
IJavaProject javaProject = JavaCore.create(projects[3]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(1, classpathEntries.length);
assertEquals("log4j-1.2.13.jar", classpathEntries[0].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(5, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-web/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
IMarker[] markers = projects[3].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
IJavaProject javaProject = JavaCore.create(projects[4]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(3, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type", classpathEntries[1].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[2].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-ejb/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/src/main/resources", rawClasspath[1].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[3].getPath().toString());
IMarker[] markers = projects[4].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
IJavaProject javaProject = JavaCore.create(projects[5]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(4, classpathEntries.length);
assertEquals("MNGECLIPSE-20-ejb", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-app", classpathEntries[1].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type", classpathEntries[2].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[3].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
IMarker[] markers = projects[5].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
}
public void testProjectImportNoWorkspaceResolution() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
IProject[] projects = importProjects("projects/MNGECLIPSE-20",
new String[] {
"pom.xml",
"type/pom.xml",
"app/pom.xml",
"web/pom.xml",
"ejb/pom.xml",
"ear/pom.xml"},
configuration);
waitForJobsToComplete();
projects[0].refreshLocal(IResource.DEPTH_INFINITE, monitor);
IResource res1 = projects[0].getFolder("ejb/target");
IResource res2 = projects[4].getFolder("target");
assertTrue(res1.exists());
assertTrue(res2.exists());
workspace.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
{
IJavaProject javaProject = JavaCore.create(projects[0]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
- IMarker[] markers = projects[0].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 0, markers.length);
+ // IMarker[] markers = projects[0].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[0]);
+ assertEquals(markers.toString(), 0, markers.size());
}
{
// type
IJavaProject javaProject = JavaCore.create(projects[1]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
- IMarker[] markers = projects[1].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 0, markers.length);
+ // IMarker[] markers = projects[1].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[1]);
+ assertEquals(markers.toString(), 0, markers.size());
}
{
// app
IJavaProject javaProject = JavaCore.create(projects[2]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(3, classpathEntries.length);
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[1].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[2].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-app/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
- IMarker[] markers = projects[2].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 3, markers.length);
+ // IMarker[] markers = projects[2].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[2]);
+ assertEquals(markers.toString(), 3, markers.size());
}
{
// web
projects[3].build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
IJavaProject javaProject = JavaCore.create(projects[3]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 5, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-web/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.web.container", rawClasspath[3].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.module.container", rawClasspath[4].getPath().toString());
- IMarker[] markers = projects[3].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 5, markers.length);
+ // IMarker[] markers = projects[3].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[3]);
+ assertEquals(markers.toString(), 4, markers.size());
}
{
// ejb
IJavaProject javaProject = JavaCore.create(projects[4]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-ejb/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/src/main/resources", rawClasspath[1].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/target/classes", rawClasspath[1].getOutputLocation().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[3].getPath().toString());
- IMarker[] markers = projects[4].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 4, markers.length);
+ // IMarker[] markers = projects[4].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[4]);
+ assertEquals(markers.toString(), 4, markers.size());
}
{
// ear
IJavaProject javaProject = JavaCore.create(projects[5]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(1, classpathEntries.length);
assertEquals("MNGECLIPSE-20-ejb-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
- IMarker[] markers = projects[5].findMarkers(null, true, IResource.DEPTH_INFINITE);
- assertEquals(toString(markers), 4, markers.length);
+ // IMarker[] markers = projects[5].findMarkers(null, true, IResource.DEPTH_INFINITE);
+ List<IMarker> markers = findErrorMarkers(projects[4]);
+ assertEquals(markers.toString(), 4, markers.size());
}
}
public void testProjectImportWithModules() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(true);
configuration.setResolveWorkspaceProjects(true);
configuration.setActiveProfiles("");
IProject project = importProject("projects/MNGECLIPSE-20/pom.xml", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(Arrays.asList(classpathEntries).toString(), 2, classpathEntries.length);
assertEquals("log4j-1.2.13.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.asList(rawClasspath).toString(), 7, rawClasspath.length);
assertEquals("/MNGECLIPSE-20/type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20/type/target/classes", rawClasspath[0].getOutputLocation().toString());
assertEquals("/MNGECLIPSE-20/app/src/main/java", rawClasspath[1].getPath().toString());
assertEquals("/MNGECLIPSE-20/app/target/classes", rawClasspath[1].getOutputLocation().toString());
assertEquals("/MNGECLIPSE-20/web/src/main/java", rawClasspath[2].getPath().toString());
assertEquals("/MNGECLIPSE-20/web/target/classes", rawClasspath[2].getOutputLocation().toString());
assertEquals("/MNGECLIPSE-20/ejb/src/main/java", rawClasspath[3].getPath().toString());
assertEquals("/MNGECLIPSE-20/ejb/target/classes", rawClasspath[3].getOutputLocation().toString());
assertEquals("/MNGECLIPSE-20/ejb/src/main/resources", rawClasspath[4].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[5].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[6].getPath().toString());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
public void testProjectImportWithModulesNoWorkspaceResolution() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(true);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
IProject project = importProject("projects/MNGECLIPSE-20/pom.xml", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals("" + Arrays.asList(classpathEntries), 2, classpathEntries.length);
assertEquals("log4j-1.2.13.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(7, rawClasspath.length);
assertEquals("/MNGECLIPSE-20/type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20/app/src/main/java", rawClasspath[1].getPath().toString());
assertEquals("/MNGECLIPSE-20/web/src/main/java", rawClasspath[2].getPath().toString());
assertEquals("/MNGECLIPSE-20/ejb/src/main/java", rawClasspath[3].getPath().toString());
assertEquals("/MNGECLIPSE-20/ejb/src/main/resources", rawClasspath[4].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[5].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[6].getPath().toString());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
public void testUpdateClasspathContainerWithModulesNoWorkspace() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(true);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
IProject project = importProject("projects/MNGECLIPSE-20/pom.xml", configuration);
waitForJobsToComplete();
// BuildPathManager buildpathManager = MavenPlugin.getDefault().getBuildpathManager();
// buildpathManager.updateClasspathContainer(project, new NullProgressMonitor());
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals("" + Arrays.asList(classpathEntries), 2, classpathEntries.length);
assertEquals("log4j-1.2.13.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[1].getPath().lastSegment());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
public void testProjectImportWithProfile1() throws Exception {
deleteProject("MNGECLIPSE-353");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(true);
configuration.setActiveProfiles("jaxb1");
IProject project = importProject("projects/MNGECLIPSE-353/pom.xml", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals("" + Arrays.asList(classpathEntries), 2, classpathEntries.length);
assertEquals("junit-3.8.1.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("jaxb-api-1.5.jar", classpathEntries[1].getPath().lastSegment());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
public void testProjectImportWithProfile2() throws Exception {
deleteProject("MNGECLIPSE-353");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(true);
configuration.setActiveProfiles("jaxb20");
IProject project = importProject("projects/MNGECLIPSE-353/pom.xml", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals("" + Arrays.asList(classpathEntries), 4, classpathEntries.length);
assertEquals("junit-3.8.1.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("jaxb-api-2.0.jar", classpathEntries[1].getPath().lastSegment());
assertEquals("jsr173_api-1.0.jar", classpathEntries[2].getPath().lastSegment());
assertEquals("activation-1.1.jar", classpathEntries[3].getPath().lastSegment());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
public void testProjectImport001_useMavenOutputFolders() throws Exception {
deleteProject("projectimport-p001");
ResolverConfiguration configuration = new ResolverConfiguration();
IProject project = importProject("projectimport-p001", "projects/projectimport/p001", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
assertEquals(new Path("/projectimport-p001/target/classes"), javaProject.getOutputLocation());
IClasspathEntry[] cp = javaProject.getRawClasspath();
assertEquals(4, cp.length);
assertEquals(new Path("/projectimport-p001/src/main/java"), cp[0].getPath());
assertEquals(new Path("/projectimport-p001/target/classes"), cp[0].getOutputLocation());
assertEquals(new Path("/projectimport-p001/src/test/java"), cp[1].getPath());
assertEquals(new Path("/projectimport-p001/target/test-classes"), cp[1].getOutputLocation());
}
public void testProjectImport002_useMavenOutputFolders() throws Exception {
deleteProject("projectimport-p002");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(true);
IProject project = importProject("projectimport-p002", "projects/projectimport/p002", configuration);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
assertEquals(new Path("/projectimport-p002/target/classes"), javaProject.getOutputLocation());
IClasspathEntry[] cp = javaProject.getRawClasspath();
assertEquals(3, cp.length);
assertEquals(new Path("/projectimport-p002/p002-m1/src/main/java"), cp[0].getPath());
assertEquals(new Path("/projectimport-p002/p002-m1/target/classes"), cp[0].getOutputLocation());
}
public void testEmbedderException() throws Exception {
deleteProject("MNGECLIPSE-157parent");
IProject project = importProject("projects/MNGECLIPSE-157parent/pom.xml", new ResolverConfiguration());
importProject("projects/MNGECLIPSE-157child/pom.xml", new ResolverConfiguration());
waitForJobsToComplete();
project.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 1, markers.length);
assertEquals(toString(markers), "pom.xml", markers[0].getResource().getFullPath().lastSegment());
}
public void testClasspathOrderWorkspace001() throws Exception {
deleteProject("p1");
deleteProject("p2");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(true);
configuration.setActiveProfiles("");
IProject project1 = importProject("projects/dependencyorder/p1/pom.xml", configuration);
IProject project2 = importProject("projects/dependencyorder/p2/pom.xml", configuration);
project1.build(IncrementalProjectBuilder.FULL_BUILD, null);
project2.build(IncrementalProjectBuilder.FULL_BUILD, null);
waitForJobsToComplete();
// MavenPlugin.getDefault().getBuildpathManager().updateClasspathContainer(p1, new NullProgressMonitor());
IJavaProject javaProject = JavaCore.create(project1);
IClasspathContainer maven2ClasspathContainer = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = maven2ClasspathContainer.getClasspathEntries();
// order according to mvn -X
assertEquals(3, cp.length);
assertEquals(new Path("/p2"), cp[0].getPath());
assertEquals("junit-4.0.jar", cp[1].getPath().lastSegment());
assertEquals("easymock-1.0.jar", cp[2].getPath().lastSegment());
}
public void testClasspathOrderWorkspace003() throws Exception {
deleteProject("p3");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(true);
configuration.setActiveProfiles("");
IProject p3 = importProject("projects/dependencyorder/p3/pom.xml", configuration);
p3.build(IncrementalProjectBuilder.FULL_BUILD, null);
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(p3);
IClasspathContainer maven2ClasspathContainer = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = maven2ClasspathContainer.getClasspathEntries();
// order according to mvn -X. note that maven 2.0.7 and 2.1-SNAPSHOT produce different order
assertEquals(6, cp.length);
assertEquals("junit-3.8.1.jar", cp[0].getPath().lastSegment());
assertEquals("commons-digester-1.6.jar", cp[1].getPath().lastSegment());
assertEquals("commons-beanutils-1.6.jar", cp[2].getPath().lastSegment());
assertEquals("commons-logging-1.0.jar", cp[3].getPath().lastSegment());
assertEquals("commons-collections-2.1.jar", cp[4].getPath().lastSegment());
assertEquals("xml-apis-1.0.b2.jar", cp[5].getPath().lastSegment());
}
public void testDownloadSources_001_basic() throws Exception {
new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete();
new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete();
IProject project = createExisting("downloadsources-p001", "projects/downloadsources/p001");
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
// sanity check
IClasspathEntry[] cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertNull(cp[0].getSourceAttachmentPath());
assertNull(cp[1].getSourceAttachmentPath());
// test project
getBuildPathManager().downloadSources(project, null);
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment());
assertEquals("downloadsources-t002-0.0.1-sources.jar", cp[1].getSourceAttachmentPath().lastSegment());
{
// cleanup
new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete();
new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete();
MavenPlugin.getDefault().getMavenProjectManager().refresh(
new MavenUpdateRequest(new IProject[] {project}, false /*offline*/, false));
waitForJobsToComplete();
}
// test one entry
getBuildPathManager().downloadSources(project, cp[0].getPath());
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment());
assertNull(cp[1].getSourceAttachmentPath());
{
// cleanup
new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete();
new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete();
MavenPlugin.getDefault().getMavenProjectManager().refresh(
new MavenUpdateRequest(new IProject[] {project}, false /*offline*/, false));
waitForJobsToComplete();
}
// test two entries
getBuildPathManager().downloadSources(project, cp[0].getPath());
getBuildPathManager().downloadSources(project, cp[1].getPath());
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertEquals("downloadsources-t001-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment());
assertEquals("downloadsources-t002-0.0.1-sources.jar", cp[1].getSourceAttachmentPath().lastSegment());
}
public void testDownloadSources_001_sourceAttachment() throws Exception {
new File(repo, "downloadsources/downloadsources-t001/0.0.1/downloadsources-t001-0.0.1-sources.jar").delete();
new File(repo, "downloadsources/downloadsources-t002/0.0.1/downloadsources-t002-0.0.1-sources.jar").delete();
IProject project = createExisting("downloadsources-p001", "projects/downloadsources/p001");
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
final IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IPath entryPath = container.getClasspathEntries()[0].getPath();
IPath srcPath = new Path("/a");
IPath srcRoot = new Path("/b");
String javaDocUrl = "c";
IClasspathAttribute attribute = JavaCore.newClasspathAttribute(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME,
javaDocUrl);
final IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, //
srcPath, srcRoot, new IAccessRule[0], //
new IClasspathAttribute[] {attribute}, //
false /*not exported*/);
BuildPathManager buildpathManager = getBuildPathManager();
IClasspathContainer containerSuggestion = new IClasspathContainer() {
public IClasspathEntry[] getClasspathEntries() {
return new IClasspathEntry[] {entry};
}
public String getDescription() {
return container.getDescription();
}
public int getKind() {
return container.getKind();
}
public IPath getPath() {
return container.getPath();
}
};
buildpathManager.updateClasspathContainer(javaProject, containerSuggestion, monitor);
waitForJobsToComplete();
// check custom source/javadoc
IClasspathContainer container2 = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry entry2 = container2.getClasspathEntries()[0];
assertEquals(entryPath, entry2.getPath());
assertEquals(srcPath, entry2.getSourceAttachmentPath());
assertEquals(srcRoot, entry2.getSourceAttachmentRootPath());
assertEquals(javaDocUrl, buildpathManager.getJavadocLocation(entry2));
File file = buildpathManager.getSourceAttachmentPropertiesFile(project);
assertEquals(true, file.canRead());
// check project delete
project.delete(true, monitor);
waitForJobsToComplete();
assertEquals(false, file.canRead());
}
public void testDownloadSources_002_javadoconly() throws Exception {
new File(repo, "downloadsources/downloadsources-t003/0.0.1/downloadsources-t003-0.0.1-javadoc.jar").delete();
IProject project = createExisting("downloadsources-p002", "projects/downloadsources/p002");
waitForJobsToComplete();
// sanity check
IJavaProject javaProject = JavaCore.create(project);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertNull(cp[0].getSourceAttachmentPath());
getBuildPathManager().downloadJavaDoc(project, null);
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertNull(cp[0].getSourceAttachmentPath()); // sanity check
assertEquals("" + cp[0], 1, getAttributeCount(cp[0], IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME));
getBuildPathManager().downloadJavaDoc(project, null);
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertNull(cp[0].getSourceAttachmentPath()); // sanity check
assertEquals("" + cp[0], 1, getAttributeCount(cp[0], IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME));
}
public void testDownloadSources_003_customRenoteRepository() throws Exception {
File file = new File(repo, "downloadsources/downloadsources-t004/0.0.1/downloadsources-t004-0.0.1-sources.jar");
assertTrue(!file.exists() || file.delete());
IProject project = createExisting("downloadsources-p003", "projects/downloadsources/p003");
waitForJobsToComplete();
// sanity check
IJavaProject javaProject = JavaCore.create(project);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertNull(cp[0].getSourceAttachmentPath());
getBuildPathManager().downloadSources(project, cp[0].getPath());
waitForJobsToComplete();
javaProject = JavaCore.create(project);
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertEquals("downloadsources-t004-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment());
}
private static int getAttributeCount(IClasspathEntry entry, String name) {
IClasspathAttribute[] attrs = entry.getExtraAttributes();
int count = 0;
for(int i = 0; i < attrs.length; i++ ) {
if(name.equals(attrs[i].getName())) {
count++ ;
}
}
return count;
}
public void testDownloadSources_004_testsClassifier() throws Exception {
File file = new File(repo, "downloadsources/downloadsources-t005/0.0.1/downloadsources-t005-0.0.1-test-sources.jar");
assertTrue(!file.exists() || file.delete());
IProject project = createExisting("downloadsources-p004", "projects/downloadsources/p004");
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = container.getClasspathEntries();
// sanity check
assertEquals("downloadsources-t005-0.0.1-tests.jar", cp[1].getPath().lastSegment());
getBuildPathManager().downloadSources(project, cp[1].getPath());
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertEquals("downloadsources-t005-0.0.1-test-sources.jar", cp[1].getSourceAttachmentPath().lastSegment());
}
public void testDownloadSources_004_classifier() throws Exception {
File file = new File(repo, "downloadsources/downloadsources-t006/0.0.1/downloadsources-t006-0.0.1-sources.jar");
assertTrue(!file.exists() || file.delete());
IProject project = createExisting("downloadsources-p005", "projects/downloadsources/p005");
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(project);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = container.getClasspathEntries();
// sanity check
assertEquals("downloadsources-t006-0.0.1-jdk14.jar", cp[0].getPath().lastSegment());
getBuildPathManager().downloadSources(project, cp[0].getPath());
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertEquals("downloadsources-t006-0.0.1-sources.jar", cp[0].getSourceAttachmentPath().lastSegment());
}
public void testDownloadSources_006_nonMavenProject() throws Exception {
IndexManager indexManager = MavenPlugin.getDefault().getIndexManager();
IndexInfo indexInfo = new IndexInfo("remoterepo-local", new File("remoterepo"), null, IndexInfo.Type.LOCAL, false);
indexManager.addIndex(indexInfo, false);
indexManager.reindex(indexInfo.getIndexName(), monitor);
indexManager.addIndex(new IndexInfo("remoterepo", null, "file:remoterepo", IndexInfo.Type.REMOTE, false), false);
IProject project = createExisting("downloadsources-p006", "projects/downloadsources/p006");
File log4jJar = new File("remoterepo/log4j/log4j/1.2.13/log4j-1.2.13.jar");
Path log4jPath = new Path(log4jJar.getAbsolutePath());
File junitJar = new File("remoterepo/junit/junit/3.8.1/junit-3.8.1.jar");
Path junitPath = new Path(junitJar.getAbsolutePath());
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] origCp = javaProject.getRawClasspath();
IClasspathEntry[] cp = new IClasspathEntry[origCp.length + 2];
System.arraycopy(origCp, 0, cp, 0, origCp.length);
cp[cp.length - 2] = JavaCore.newLibraryEntry(log4jPath, null, null, true);
cp[cp.length - 1] = JavaCore.newLibraryEntry(junitPath, null, null, false);
javaProject.setRawClasspath(cp, monitor);
getBuildPathManager().downloadSources(project, log4jPath);
waitForJobsToComplete();
cp = javaProject.getRawClasspath();
assertEquals(log4jPath, cp[cp.length - 2].getPath());
assertEquals("log4j-1.2.13-sources.jar", cp[cp.length - 2].getSourceAttachmentPath().lastSegment());
assertEquals(true, cp[cp.length - 2].isExported());
getBuildPathManager().downloadSources(project, junitPath);
waitForJobsToComplete();
assertEquals(junitPath, cp[cp.length - 1].getPath());
assertEquals("junit-3.8.1-sources.jar", cp[cp.length - 1].getSourceAttachmentPath().lastSegment());
assertEquals(false, cp[cp.length - 1].isExported());
}
private BuildPathManager getBuildPathManager() {
return MavenJdtPlugin.getDefault().getBuildpathManager();
}
public void testClassifiers() throws Exception {
IProject p1 = createExisting("classifiers-p1", "projects/classifiers/classifiers-p1");
waitForJobsToComplete();
IJavaProject javaProject = JavaCore.create(p1);
IClasspathContainer container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
IClasspathEntry[] cp = container.getClasspathEntries();
assertEquals(2, cp.length);
assertEquals("classifiers-p2-0.0.1.jar", cp[0].getPath().lastSegment());
assertEquals("classifiers-p2-0.0.1-tests.jar", cp[1].getPath().lastSegment());
createExisting("classifiers-p2", "projects/classifiers/classifiers-p2");
waitForJobsToComplete();
container = BuildPathManager.getMaven2ClasspathContainer(javaProject);
cp = container.getClasspathEntries();
assertEquals(1, cp.length);
assertEquals("classifiers-p2", cp[0].getPath().lastSegment());
}
public void testCreateSimpleProject() throws CoreException {
final MavenPlugin plugin = MavenPlugin.getDefault();
final boolean modules = true;
IProject project = createSimpleProject("simple-project", null, modules);
ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project);
assertEquals(modules, configuration.shouldIncludeModules());
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 6, rawClasspath.length);
assertEquals("/simple-project/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/simple-project/src/main/resources", rawClasspath[1].getPath().toString());
assertEquals("/simple-project/src/test/java", rawClasspath[2].getPath().toString());
assertEquals("/simple-project/src/test/resources", rawClasspath[3].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[4].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[5].getPath().toString());
IClasspathEntry[] entries = getMavenContainerEntries(project);
assertEquals(Arrays.toString(entries), 1, entries.length);
assertEquals(IClasspathEntry.CPE_LIBRARY, entries[0].getEntryKind());
assertEquals("junit-3.8.1.jar", entries[0].getPath().lastSegment());
assertTrue(project.getFile("pom.xml").exists());
assertTrue(project.getFolder("src/main/java").exists());
assertTrue(project.getFolder("src/test/java").exists());
assertTrue(project.getFolder("src/main/resources").exists());
assertTrue(project.getFolder("src/test/resources").exists());
}
public void test005_dependencyAvailableFromLocalRepoAndWorkspace() throws Exception {
IProject p1 = createExisting("t005-p1", "resources/t005/t005-p1");
IProject p2 = createExisting("t005-p2", "resources/t005/t005-p2");
waitForJobsToComplete();
IClasspathEntry[] cp = getMavenContainerEntries(p1);
assertEquals(1, cp.length);
assertEquals(p2.getFullPath(), cp[0].getPath());
p2.close(monitor);
waitForJobsToComplete();
cp = getMavenContainerEntries(p1);
assertEquals(1, cp.length);
assertEquals("t005-p2-0.0.1.jar", cp[0].getPath().lastSegment());
p2.open(monitor);
waitForJobsToComplete();
cp = getMavenContainerEntries(p1);
assertEquals(1, cp.length);
assertEquals(p2.getFullPath(), cp[0].getPath());
}
public void testProjectNameTemplate() throws Exception {
deleteProject("p003");
deleteProject("projectimport.p003-2.0");
ResolverConfiguration configuration = new ResolverConfiguration();
ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration);
importProject("p003version1", "projects/projectimport/p003version1", projectImportConfiguration);
projectImportConfiguration.setProjectNameTemplate("[groupId].[artifactId]-[version]");
importProject("p003version2", "projects/projectimport/p003version2", projectImportConfiguration);
waitForJobsToComplete();
assertTrue(workspace.getRoot().getProject("p003").exists());
assertTrue(workspace.getRoot().getProject("projectimport.p003-2.0").exists());
}
public void testCompilerSettingsJsr14() throws Exception {
deleteProject("compilerSettingsJsr14");
ResolverConfiguration configuration = new ResolverConfiguration();
ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration);
importProject("compilerSettingsJsr14", "projects/compilerSettingsJsr14", projectImportConfiguration);
waitForJobsToComplete();
IProject project = workspace.getRoot().getProject("compilerSettingsJsr14");
assertTrue(project.exists());
// IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> errorMarkers = findErrorMarkers(project);
assertEquals(errorMarkers.toString(), 0, errorMarkers.size());
IJavaProject javaProject = JavaCore.create(project);
assertEquals("1.5", javaProject.getOption(JavaCore.COMPILER_SOURCE, true));
assertEquals("1.5", javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
IClasspathEntry jreEntry = getJreContainer(javaProject.getRawClasspath());
assertEquals("J2SE-1.5", JavaRuntime.getExecutionEnvironmentId(jreEntry.getPath()));
}
public void testCompilerSettings14() throws Exception {
deleteProject("compilerSettings14");
ResolverConfiguration configuration = new ResolverConfiguration();
ProjectImportConfiguration projectImportConfiguration = new ProjectImportConfiguration(configuration);
importProject("compilerSettings14", "projects/compilerSettings14", projectImportConfiguration);
waitForJobsToComplete();
IProject project = workspace.getRoot().getProject("compilerSettings14");
assertTrue(project.exists());
// Build path specifies execution environment J2SE-1.4.
// There are no JREs in the workspace strictly compatible with this environment.
IMarker[] markers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 1, markers.length);
IJavaProject javaProject = JavaCore.create(project);
assertEquals("1.4", javaProject.getOption(JavaCore.COMPILER_SOURCE, true));
assertEquals("1.4", javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
IClasspathEntry jreEntry = getJreContainer(javaProject.getRawClasspath());
assertEquals("J2SE-1.4", JavaRuntime.getExecutionEnvironmentId(jreEntry.getPath()));
}
private IClasspathEntry getJreContainer(IClasspathEntry[] entries) {
for(IClasspathEntry entry : entries) {
if(JavaRuntime.newDefaultJREContainerPath().isPrefixOf(entry.getPath())) {
return entry;
}
}
return null;
}
public void testMavenBuilderOrder() throws Exception {
IProject project = createExisting("builderOrder", "projects/builderOrder");
IProjectDescription description = project.getDescription();
ICommand[] buildSpec = description.getBuildSpec();
ICommand javaBuilder = buildSpec[0];
ICommand mavenBuilder = buildSpec[1];
verifyNaturesAndBuilders(project);
ResolverConfiguration configuration = new ResolverConfiguration();
String goalToExecute = "";
IProjectConfigurationManager configurationManager = plugin.getProjectConfigurationManager();
configurationManager.updateProjectConfiguration(project, configuration, goalToExecute, monitor);
verifyNaturesAndBuilders(project);
description.setNatureIds(new String[] {JavaCore.NATURE_ID});
description.setBuildSpec(new ICommand[] {javaBuilder});
project.setDescription(description, monitor);
// can't update configuration of non-maven project
configurationManager.enableMavenNature(project, configuration, monitor);
verifyNaturesAndBuilders(project);
description.setNatureIds(new String[] {});
description.setBuildSpec(new ICommand[] {mavenBuilder, javaBuilder});
project.setDescription(description, monitor);
// can't update configuration of non-maven project
configurationManager.enableMavenNature(project, configuration, monitor);
verifyNaturesAndBuilders(project);
description.setNatureIds(new String[] {IMavenConstants.NATURE_ID, JavaCore.NATURE_ID});
description.setBuildSpec(new ICommand[] {mavenBuilder, javaBuilder});
project.setDescription(description, monitor);
// can't update configuration of non-maven project
configurationManager.enableMavenNature(project, configuration, monitor);
verifyNaturesAndBuilders(project);
}
private void verifyNaturesAndBuilders(IProject project) throws CoreException {
assertTrue(project.hasNature(JavaCore.NATURE_ID));
assertTrue(project.hasNature(IMavenConstants.NATURE_ID));
IProjectDescription description = project.getDescription();
{
ICommand[] buildSpec = description.getBuildSpec();
assertEquals(2, buildSpec.length);
assertEquals(JavaCore.BUILDER_ID, buildSpec[0].getBuilderName());
assertEquals(IMavenConstants.BUILDER_ID, buildSpec[1].getBuilderName());
}
}
private IProject createSimpleProject(final String projectName, final IPath location, final boolean modules)
throws CoreException {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
workspace.run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
Model model = new Model();
model.setGroupId(projectName);
model.setArtifactId(projectName);
model.setVersion("0.0.1-SNAPSHOT");
model.setModelVersion("4.0.0");
Dependency dependency = new Dependency();
dependency.setGroupId("junit");
dependency.setArtifactId("junit");
dependency.setVersion("3.8.1");
model.addDependency(dependency);
String[] directories = {"src/main/java", "src/test/java", "src/main/resources", "src/test/resources"};
ProjectImportConfiguration config = new ProjectImportConfiguration();
config.getResolverConfiguration().setIncludeModules(modules);
plugin.getProjectConfigurationManager().createSimpleProject(project, location, model, directories,
config, monitor);
}
}, plugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor);
return project;
}
public void testSimpleProjectInExternalLocation() throws CoreException, IOException {
final MavenPlugin plugin = MavenPlugin.getDefault();
final boolean modules = true;
File tmp = File.createTempFile("m2eclipse", "test");
tmp.delete(); //deleting a tmp file so we can use the name for a folder
final String projectName1 = "external-simple-project-1";
IProject project1 = createSimpleProject(projectName1, new Path(tmp.getAbsolutePath()).append(projectName1), modules);
ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project1);
assertEquals(modules, configuration.shouldIncludeModules());
final String projectName2 = "external-simple-project-2";
File existingFolder = new File(tmp, projectName2);
existingFolder.mkdirs();
new File(existingFolder, IMavenConstants.POM_FILE_NAME).createNewFile();
try {
createSimpleProject(projectName2, new Path(tmp.getAbsolutePath()).append(projectName2), modules);
fail("Project creation should fail if the POM exists in the target folder");
} catch(CoreException e) {
final String msg = IMavenConstants.POM_FILE_NAME + " already exists";
assertTrue("Project creation should throw a \"" + msg + "\" exception if the POM exists in the target folder", e
.getMessage().indexOf(msg) > 0);
}
tmp.delete();
}
public void testArchetypeProject() throws CoreException {
MavenPlugin plugin = MavenPlugin.getDefault();
boolean modules = true;
Archetype quickStart = findQuickStartArchetype();
IProject project = createArchetypeProject("archetype-project", null, quickStart, modules);
ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project);
assertEquals(modules, configuration.shouldIncludeModules());
}
public void testArchetypeProjectInExternalLocation() throws CoreException, IOException {
final MavenPlugin plugin = MavenPlugin.getDefault();
final boolean modules = true;
Archetype quickStart = findQuickStartArchetype();
File tmp = File.createTempFile("m2eclipse", "test");
tmp.delete(); //deleting a tmp file so we can use the name for a folder
final String projectName1 = "external-archetype-project-1";
IProject project1 = createArchetypeProject(projectName1, new Path(tmp.getAbsolutePath()).append(projectName1),
quickStart, modules);
ResolverConfiguration configuration = plugin.getMavenProjectManager().getResolverConfiguration(project1);
assertEquals(modules, configuration.shouldIncludeModules());
final String projectName2 = "external-archetype-project-2";
File existingFolder = new File(tmp, projectName2);
existingFolder.mkdirs();
new File(existingFolder, IMavenConstants.POM_FILE_NAME).createNewFile();
try {
createArchetypeProject(projectName2, new Path(tmp.getAbsolutePath()).append(projectName2), quickStart, modules);
fail("Project creation should fail if the POM exists in the target folder");
} catch(CoreException e) {
// this is supposed to happen
}
tmp.delete();
}
private Archetype findQuickStartArchetype() throws CoreException {
final MavenPlugin plugin = MavenPlugin.getDefault();
@SuppressWarnings("unchecked")
List<Archetype> archetypes = plugin.getArchetypeManager().getArchetypeCatalogFactory("internal")
.getArchetypeCatalog(plugin.getMavenEmbedderManager()).getArchetypes();
for(Archetype archetype : archetypes) {
if("org.apache.maven.archetypes".equals(archetype.getGroupId())
&& "maven-archetype-quickstart".equals(archetype.getArtifactId()) && "1.0".equals(archetype.getVersion())) {
return archetype;
}
}
fail("maven-archetype-quickstart archetype not found in the internal catalog");
return null;
}
private IProject createArchetypeProject(final String projectName, final IPath location, final Archetype archetype,
final boolean modules) throws CoreException {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
workspace.run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
ResolverConfiguration resolverConfiguration = new ResolverConfiguration();
resolverConfiguration.setIncludeModules(modules);
ProjectImportConfiguration pic = new ProjectImportConfiguration(resolverConfiguration);
plugin.getProjectConfigurationManager().createArchetypeProject(project, location, archetype, //
projectName, projectName, "0.0.1-SNAPSHOT", "jar", new Properties(), pic, monitor);
}
}, plugin.getProjectConfigurationManager().getRule(), IWorkspace.AVOID_UPDATE, monitor);
return project;
}
private List<IMarker> findErrorMarkers(IProject project) throws CoreException {
ArrayList<IMarker> errors = new ArrayList<IMarker>();
for(IMarker marker : project.findMarkers(null /* all markers */, true /* subtypes */, IResource.DEPTH_INFINITE)) {
int severity = marker.getAttribute(IMarker.SEVERITY, 0);
if(severity==IMarker.SEVERITY_ERROR) {
errors.add(marker);
}
}
return errors;
}
}
| false | true | public void testProjectImportNoWorkspaceResolution() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
IProject[] projects = importProjects("projects/MNGECLIPSE-20",
new String[] {
"pom.xml",
"type/pom.xml",
"app/pom.xml",
"web/pom.xml",
"ejb/pom.xml",
"ear/pom.xml"},
configuration);
waitForJobsToComplete();
projects[0].refreshLocal(IResource.DEPTH_INFINITE, monitor);
IResource res1 = projects[0].getFolder("ejb/target");
IResource res2 = projects[4].getFolder("target");
assertTrue(res1.exists());
assertTrue(res2.exists());
workspace.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
{
IJavaProject javaProject = JavaCore.create(projects[0]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
IMarker[] markers = projects[0].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
// type
IJavaProject javaProject = JavaCore.create(projects[1]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
IMarker[] markers = projects[1].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 0, markers.length);
}
{
// app
IJavaProject javaProject = JavaCore.create(projects[2]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(3, classpathEntries.length);
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[1].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[2].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-app/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
IMarker[] markers = projects[2].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 3, markers.length);
}
{
// web
projects[3].build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
IJavaProject javaProject = JavaCore.create(projects[3]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 5, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-web/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.web.container", rawClasspath[3].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.module.container", rawClasspath[4].getPath().toString());
IMarker[] markers = projects[3].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 5, markers.length);
}
{
// ejb
IJavaProject javaProject = JavaCore.create(projects[4]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-ejb/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/src/main/resources", rawClasspath[1].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/target/classes", rawClasspath[1].getOutputLocation().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[3].getPath().toString());
IMarker[] markers = projects[4].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 4, markers.length);
}
{
// ear
IJavaProject javaProject = JavaCore.create(projects[5]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(1, classpathEntries.length);
assertEquals("MNGECLIPSE-20-ejb-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
IMarker[] markers = projects[5].findMarkers(null, true, IResource.DEPTH_INFINITE);
assertEquals(toString(markers), 4, markers.length);
}
}
| public void testProjectImportNoWorkspaceResolution() throws Exception {
deleteProject("MNGECLIPSE-20");
deleteProject("MNGECLIPSE-20-app");
deleteProject("MNGECLIPSE-20-ear");
deleteProject("MNGECLIPSE-20-ejb");
deleteProject("MNGECLIPSE-20-type");
deleteProject("MNGECLIPSE-20-web");
ResolverConfiguration configuration = new ResolverConfiguration();
configuration.setIncludeModules(false);
configuration.setResolveWorkspaceProjects(false);
configuration.setActiveProfiles("");
IProject[] projects = importProjects("projects/MNGECLIPSE-20",
new String[] {
"pom.xml",
"type/pom.xml",
"app/pom.xml",
"web/pom.xml",
"ejb/pom.xml",
"ear/pom.xml"},
configuration);
waitForJobsToComplete();
projects[0].refreshLocal(IResource.DEPTH_INFINITE, monitor);
IResource res1 = projects[0].getFolder("ejb/target");
IResource res2 = projects[4].getFolder("target");
assertTrue(res1.exists());
assertTrue(res2.exists());
workspace.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
{
IJavaProject javaProject = JavaCore.create(projects[0]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
// IMarker[] markers = projects[0].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[0]);
assertEquals(markers.toString(), 0, markers.size());
}
{
// type
IJavaProject javaProject = JavaCore.create(projects[1]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(0, classpathEntries.length);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-type/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
// IMarker[] markers = projects[1].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[1]);
assertEquals(markers.toString(), 0, markers.size());
}
{
// app
IJavaProject javaProject = JavaCore.create(projects[2]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(3, classpathEntries.length);
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("log4j-1.2.13.jar", classpathEntries[1].getPath().lastSegment());
assertEquals("junit-3.8.1.jar", classpathEntries[2].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(3, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-app/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
// IMarker[] markers = projects[2].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[2]);
assertEquals(markers.toString(), 3, markers.size());
}
{
// web
projects[3].build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
IJavaProject javaProject = JavaCore.create(projects[3]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(Arrays.toString(rawClasspath), 5, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-web/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[1].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.web.container", rawClasspath[3].getPath().toString());
assertEquals("org.eclipse.jst.j2ee.internal.module.container", rawClasspath[4].getPath().toString());
// IMarker[] markers = projects[3].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[3]);
assertEquals(markers.toString(), 4, markers.size());
}
{
// ejb
IJavaProject javaProject = JavaCore.create(projects[4]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(2, classpathEntries.length);
assertEquals("MNGECLIPSE-20-app-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
assertEquals("MNGECLIPSE-20-type-0.0.1-SNAPSHOT.jar", classpathEntries[1].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(4, rawClasspath.length);
assertEquals("/MNGECLIPSE-20-ejb/src/main/java", rawClasspath[0].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/src/main/resources", rawClasspath[1].getPath().toString());
assertEquals("/MNGECLIPSE-20-ejb/target/classes", rawClasspath[1].getOutputLocation().toString());
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[2].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[3].getPath().toString());
// IMarker[] markers = projects[4].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[4]);
assertEquals(markers.toString(), 4, markers.size());
}
{
// ear
IJavaProject javaProject = JavaCore.create(projects[5]);
IClasspathEntry[] classpathEntries = BuildPathManager.getMaven2ClasspathContainer(javaProject)
.getClasspathEntries();
assertEquals(1, classpathEntries.length);
assertEquals("MNGECLIPSE-20-ejb-0.0.1-SNAPSHOT.jar", classpathEntries[0].getPath().lastSegment());
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
assertEquals(2, rawClasspath.length);
assertEquals("org.eclipse.jdt.launching.JRE_CONTAINER", rawClasspath[0].getPath().toString());
assertEquals("org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER", rawClasspath[1].getPath().toString());
// IMarker[] markers = projects[5].findMarkers(null, true, IResource.DEPTH_INFINITE);
List<IMarker> markers = findErrorMarkers(projects[4]);
assertEquals(markers.toString(), 4, markers.size());
}
}
|
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
index 7794f561d..80ab67b69 100644
--- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
+++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
@@ -1,184 +1,188 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caIntegrator2
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caIntegrator2 Software License (the License) is between NCI and You. You (or
* Your) shall mean a person or an entity, and all other entities that control,
* are controlled by, or are under common control with the entity. Control for
* purposes of this definition means (i) the direct or indirect power to cause
* the direction or management of such entity, whether by contract or otherwise,
* or (ii) ownership of fifty percent (50%) or more of the outstanding shares,
* or (iii) beneficial ownership of such entity.
*
* This License is granted provided that You agree to the conditions described
* below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up,
* no-charge, irrevocable, transferable and royalty-free right and license in
* its rights in the caIntegrator2 Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caIntegrator2 Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator2 Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the Software must retain the
* above copyright notice, this list of conditions and the disclaimer and
* limitation of liability of Article 6, below. Your redistributions in object
* code form must reproduce the above copyright notice, this list of conditions
* and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the Software into third party
* proprietary programs, You agree that You are solely responsible for obtaining
* any permission from such third parties required to incorporate the Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* For sake of clarity, and not by way of limitation, You may add Your own
* copyright statement to Your modifications and to the derivative works, and
* You may provide additional or different license terms and conditions in Your
* sublicenses of modifications of the Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO
* EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES 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 gov.nih.nci.caintegrator2.application.workspace;
import gov.nih.nci.caintegrator2.data.CaIntegrator2Dao;
import gov.nih.nci.caintegrator2.domain.application.StudySubscription;
import gov.nih.nci.caintegrator2.domain.application.UserWorkspace;
import gov.nih.nci.caintegrator2.domain.translational.Study;
import gov.nih.nci.caintegrator2.security.SecurityHelper;
import java.util.HashSet;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation entry point for the WorkspaceService subsystem.
*/
@Transactional(propagation = Propagation.REQUIRED)
public class WorkspaceServiceImpl implements WorkspaceService {
private CaIntegrator2Dao dao;
/**
* {@inheritDoc}
*/
public UserWorkspace getWorkspace() {
String username = SecurityHelper.getCurrentUsername();
UserWorkspace userWorkspace = dao.getWorkspace(username);
if (userWorkspace == null) {
userWorkspace = createUserWorkspace(username);
saveUserWorkspace(userWorkspace);
}
return userWorkspace;
}
private UserWorkspace createUserWorkspace(String username) {
UserWorkspace userWorkspace;
userWorkspace = new UserWorkspace();
userWorkspace.setUsername(username);
userWorkspace.setSubscriptionCollection(new HashSet<StudySubscription>());
return userWorkspace;
}
/**
* @return the dao
*/
public CaIntegrator2Dao getDao() {
return dao;
}
/**
* @param dao the dao to set
*/
public void setDao(CaIntegrator2Dao dao) {
this.dao = dao;
}
/**
* @param workspace saves workspace.
*/
public void saveUserWorkspace(UserWorkspace workspace) {
dao.save(workspace);
}
/**
* {@inheritDoc}
*/
public void subscribe(UserWorkspace workspace, Study study) {
if (!isSubscribed(workspace, study)) {
StudySubscription subscription = new StudySubscription();
subscription.setStudy(study);
workspace.getSubscriptionCollection().add(subscription);
saveUserWorkspace(workspace);
}
}
/**
* {@inheritDoc}
*/
public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
+ if (workspace.getDefaultSubscription() != null
+ && workspace.getDefaultSubscription().equals(subscription)) {
+ workspace.setDefaultSubscription(null);
+ }
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
private boolean isSubscribed(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
return true;
}
}
return false;
}
}
| true | true | public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
| public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
if (workspace.getDefaultSubscription() != null
&& workspace.getDefaultSubscription().equals(subscription)) {
workspace.setDefaultSubscription(null);
}
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
|
diff --git a/cmm/src/main/java/de/escidoc/core/cmm/business/fedora/FedoraContentModelHandler.java b/cmm/src/main/java/de/escidoc/core/cmm/business/fedora/FedoraContentModelHandler.java
index c12160f..afc2845 100644
--- a/cmm/src/main/java/de/escidoc/core/cmm/business/fedora/FedoraContentModelHandler.java
+++ b/cmm/src/main/java/de/escidoc/core/cmm/business/fedora/FedoraContentModelHandler.java
@@ -1,902 +1,905 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2008 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
/**
*
*/
package de.escidoc.core.cmm.business.fedora;
import de.escidoc.core.cmm.business.fedora.contentModel.ContentModelHandlerRetrieve;
import de.escidoc.core.cmm.business.interfaces.ContentModelHandlerInterface;
import de.escidoc.core.cmm.business.stax.handler.contentModel.ContentModelCreateHandler;
import de.escidoc.core.cmm.business.stax.handler.contentModel.ContentModelPropertiesHandler;
import de.escidoc.core.cmm.business.stax.handler.contentModel.MdRecordDefinitionHandler;
import de.escidoc.core.cmm.business.stax.handler.contentModel.ResourceDefinitionHandler;
import de.escidoc.core.common.business.Constants;
import de.escidoc.core.common.business.fedora.TripleStoreUtility;
import de.escidoc.core.common.business.fedora.Utility;
import de.escidoc.core.common.business.fedora.datastream.Datastream;
import de.escidoc.core.common.business.fedora.resources.ResourceType;
import de.escidoc.core.common.business.fedora.resources.StatusType;
import de.escidoc.core.common.business.fedora.resources.create.ContentModelCreate;
import de.escidoc.core.common.business.fedora.resources.create.ContentStreamCreate;
import de.escidoc.core.common.business.fedora.resources.create.MdRecordCreate;
import de.escidoc.core.common.business.fedora.resources.create.MdRecordDefinitionCreate;
import de.escidoc.core.common.business.fedora.resources.create.ResourceDefinitionCreate;
import de.escidoc.core.common.business.fedora.resources.listener.ResourceListener;
import de.escidoc.core.common.business.filter.SRURequest;
import de.escidoc.core.common.business.filter.SRURequestParameters;
import de.escidoc.core.common.business.stax.handler.common.ContentStreamsHandler;
import de.escidoc.core.common.business.stax.handler.context.DcUpdateHandler;
import de.escidoc.core.common.exceptions.application.invalid.InvalidContentException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidStatusException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidXmlException;
import de.escidoc.core.common.exceptions.application.invalid.XmlCorruptedException;
import de.escidoc.core.common.exceptions.application.missing.MissingAttributeValueException;
import de.escidoc.core.common.exceptions.application.notfound.ContentModelNotFoundException;
import de.escidoc.core.common.exceptions.application.notfound.ContentStreamNotFoundException;
import de.escidoc.core.common.exceptions.application.notfound.ResourceNotFoundException;
import de.escidoc.core.common.exceptions.application.notfound.StreamNotFoundException;
import de.escidoc.core.common.exceptions.application.violated.LockingException;
import de.escidoc.core.common.exceptions.application.violated.OptimisticLockingException;
import de.escidoc.core.common.exceptions.application.violated.ReadonlyVersionException;
import de.escidoc.core.common.exceptions.application.violated.ResourceInUseException;
import de.escidoc.core.common.exceptions.system.EncodingSystemException;
import de.escidoc.core.common.exceptions.system.FedoraSystemException;
import de.escidoc.core.common.exceptions.system.IntegritySystemException;
import de.escidoc.core.common.exceptions.system.SystemException;
import de.escidoc.core.common.exceptions.system.TripleStoreSystemException;
import de.escidoc.core.common.exceptions.system.WebserverSystemException;
import de.escidoc.core.common.exceptions.system.XmlParserSystemException;
import de.escidoc.core.common.util.configuration.EscidocConfiguration;
import de.escidoc.core.common.util.stax.StaxParser;
import de.escidoc.core.common.util.stax.handler.MultipleExtractor;
import de.escidoc.core.common.util.stax.handler.OptimisticLockingHandler;
import de.escidoc.core.common.util.xml.Elements;
import de.escidoc.core.common.util.xml.XmlUtility;
import de.escidoc.core.common.util.xml.factory.ContentModelFoXmlProvider;
import de.escidoc.core.common.util.xml.factory.XmlTemplateProviderConstants;
import de.escidoc.core.common.util.xml.stax.events.Attribute;
import de.escidoc.core.common.util.xml.stax.events.StartElementWithChildElements;
import de.escidoc.core.common.util.xml.stax.events.StartElementWithText;
import org.escidoc.core.services.fedora.FedoraServiceClient;
import org.escidoc.core.services.fedora.IngestPathParam;
import org.escidoc.core.services.fedora.IngestQueryParam;
import org.escidoc.core.services.fedora.ModifiyDatastreamPathParam;
import org.escidoc.core.services.fedora.ModifyDatastreamQueryParam;
import org.esidoc.core.utils.io.EscidocBinaryContent;
import org.esidoc.core.utils.io.MimeTypes;
import org.esidoc.core.utils.io.Stream;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* @author Frank Schwichtenberg
*/
@Service("business.FedoraContentModelHandler")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class FedoraContentModelHandler extends ContentModelHandlerRetrieve implements ContentModelHandlerInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(FedoraContentModelHandler.class);
private final Collection<ResourceListener> contentModelListeners = new ArrayList<ResourceListener>();
@Autowired
@Qualifier("de.escidoc.core.common.business.filter.SRURequest")
private SRURequest sruRequest;
@Autowired
@Qualifier("common.business.indexing.IndexingHandler")
private ResourceListener indexingHandler;
@Autowired
private FedoraServiceClient fedoraServiceClient;
@Autowired
@Qualifier("business.TripleStoreUtility")
private TripleStoreUtility tripleStoreUtility;
/**
* Protected constructor to prevent instantiation outside of the Spring-context.
*/
protected FedoraContentModelHandler() {
}
@PostConstruct
private void init() {
contentModelListeners.add(this.indexingHandler);
}
/**
* See Interface for functional description.
*/
@Override
public String retrieve(final String id) throws ContentModelNotFoundException, SystemException {
setContentModel(id);
return render();
}
@Override
public String retrieveContentStream(final String id, final String name) throws ContentModelNotFoundException,
TripleStoreSystemException, IntegritySystemException, WebserverSystemException, FedoraSystemException {
setContentModel(id);
return renderContentStream(name, true);
}
@Override
public EscidocBinaryContent retrieveContentStreamContent(final String id, final String name)
throws ContentModelNotFoundException, ContentStreamNotFoundException, InvalidStatusException,
FedoraSystemException, TripleStoreSystemException, WebserverSystemException, IntegritySystemException {
setContentModel(id);
if (getContentModel().isWithdrawn()) {
final String msg =
"The object is in state '" + Constants.STATUS_WITHDRAWN + "'. Content is not accessible.";
throw new InvalidStatusException(msg);
}
return getContentStream(name);
}
private EscidocBinaryContent getContentStream(final String name) throws WebserverSystemException {
final Datastream cs = getContentModel().getContentStream(name);
final EscidocBinaryContent bin = new EscidocBinaryContent();
final String fileName = cs.getLabel();
bin.setFileName(fileName);
final String mimeType = cs.getMimeType();
bin.setMimeType(mimeType);
if ("R".equals(cs.getControlGroup())) {
bin.setRedirectUrl(cs.getLocation());
}
else {
final Stream stream =
this.fedoraServiceClient.getBinaryContent(getContentModel().getId(), name, getContentModel()
.getVersionDate());
try {
bin.setContent(stream.getInputStream());
}
catch (IOException e) {
throw new WebserverSystemException("Error on loading binary content.", e);
}
}
return bin;
}
private EscidocBinaryContent retrieveOtherContent(final String dsName) throws WebserverSystemException {
final Datastream ds = getContentModel().getOtherStream(dsName);
return getContent(ds);
}
private EscidocBinaryContent getContent(final Datastream ds) throws WebserverSystemException {
final EscidocBinaryContent bin = new EscidocBinaryContent();
final String name = ds.getName();
final String fileName = ds.getLabel();
bin.setFileName(fileName);
final String mimeType = ds.getMimeType();
bin.setMimeType(mimeType);
if ("R".equals(ds.getControlGroup())) {
bin.setRedirectUrl(ds.getLocation());
}
else {
final Stream stream =
this.fedoraServiceClient.getBinaryContent(ds.getParentId(), name, getContentModel().getVersionDate());
try {
bin.setContent(stream.getInputStream());
}
catch (IOException e) {
throw new WebserverSystemException("Error on loading binary content.", e);
}
}
return bin;
}
@Override
public String retrieveResources(final String id) throws ContentModelNotFoundException, SystemException {
setContentModel(id);
return renderResources();
}
public String retrieveResourceDefinitions(final String id) throws ContentModelNotFoundException,
TripleStoreSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException {
setContentModel(id);
return renderResourceDefinitions();
}
public String retrieveResourceDefinition(final String id, final String name) throws ContentModelNotFoundException,
TripleStoreSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException {
setContentModel(id);
return renderResourceDefinition(name);
}
@Override
public EscidocBinaryContent retrieveMdRecordDefinitionSchemaContent(final String id, final String name)
throws ContentModelNotFoundException, WebserverSystemException, TripleStoreSystemException,
IntegritySystemException, FedoraSystemException {
setContentModel(id);
return retrieveOtherContent(name + "_xsd");
}
@Override
public EscidocBinaryContent retrieveResourceDefinitionXsltContent(final String id, final String name)
throws ResourceNotFoundException, FedoraSystemException, WebserverSystemException, TripleStoreSystemException,
IntegritySystemException {
setContentModel(id);
// xslt is stored in sdef
// sDef ID is build from CM ID and operation name
final String sDefId =
"sdef:" + getContentModel().getId().replaceAll(":", Constants.COLON_REPLACEMENT_PID) + '-' + name;
// get the 'xslt' datastream from sDef
final Datastream ds;
try {
ds = new Datastream("xslt", sDefId, null);
}
catch (final StreamNotFoundException e) {
throw new ResourceNotFoundException("No XSLT for operation '" + name + "' in content model " + id + '.', e);
}
return getContent(ds);
}
@Override
public String retrieveVersionHistory(final String id) throws ContentModelNotFoundException,
EncodingSystemException, IntegritySystemException, FedoraSystemException, WebserverSystemException,
TripleStoreSystemException {
setContentModel(id);
final String versionsXml;
try {
versionsXml =
getContentModel().getWov().toStringUTF8().replaceFirst(
'<' + Constants.WOV_NAMESPACE_PREFIX + ':' + Elements.ELEMENT_WOV_VERSION_HISTORY,
'<' + Constants.WOV_NAMESPACE_PREFIX + ':' + Elements.ELEMENT_WOV_VERSION_HISTORY + " xml:base=\""
+ XmlUtility.getEscidocBaseUrl() + "\" " + Elements.ATTRIBUTE_LAST_MODIFICATION_DATE + "=\""
+ getContentModel().getLastModificationDate() + "\" ");
}
catch (final StreamNotFoundException e) {
throw new IntegritySystemException("Version history not found.", e);
}
return versionsXml;
}
/**
* Retrieves a filtered list of Content Models.
*
* @param parameters parameters from the SRU request
* @return Returns XML representation of the list of Content Model objects.
*/
@Override
public String retrieveContentModels(final SRURequestParameters parameters) throws WebserverSystemException {
final StringWriter result = new StringWriter();
if (parameters.isExplain()) {
sruRequest.explain(result, ResourceType.CONTENT_MODEL);
}
else {
sruRequest.searchRetrieve(result, new ResourceType[] { ResourceType.CONTENT_MODEL }, parameters);
}
return result.toString();
}
/**
* See Interface for functional description.
*/
@Override
public String create(final String xmlData) throws InvalidContentException, MissingAttributeValueException,
SystemException, XmlCorruptedException {
final ContentModelCreate contentModel = parseContentModel(xmlData);
// check that the objid was not obtained from the representation
contentModel.setObjid(null);
contentModel.setIdProvider(getIdProvider());
validate(contentModel);
contentModel.persist(true);
final String objid = contentModel.getObjid();
final String resultContentModel;
try {
resultContentModel = retrieve(objid);
}
catch (final ResourceNotFoundException e) {
final String msg =
"The Content Model with id '" + objid + "', which was just created, "
+ "could not be found for retrieve.";
throw new IntegritySystemException(msg, e);
}
fireContentModelCreated(objid, resultContentModel);
return resultContentModel;
}
/**
* See Interface for functional description.
*/
@Override
public void delete(final String id) throws ContentModelNotFoundException, SystemException, LockingException,
InvalidStatusException, ResourceInUseException {
setContentModel(id);
checkLocked();
if (!(getContentModel().isPending() || getContentModel().isInRevision())) {
throw new InvalidStatusException("Content Model must be is public status pending or "
+ "submitted in order to delete it.");
}
// check if objects refer this content model
if (this.tripleStoreUtility.hasReferringResource(id)) {
throw new ResourceInUseException("The content model is referred by "
+ "an resource and can not be deleted.");
}
// delete every behavior (sdef, sdep) even those from old versions
this.fedoraServiceClient.deleteObject(getContentModel().getId());
this.fedoraServiceClient.sync();
this.tripleStoreUtility.reinitialize();
fireContentModelDeleted(getContentModel().getId());
}
/**
* See Interface for functional description.
*/
@Override
public String update(final String id, final String xmlData) throws ContentModelNotFoundException,
OptimisticLockingException, SystemException, ReadonlyVersionException, MissingAttributeValueException,
InvalidXmlException, InvalidContentException {
setContentModel(id);
final DateTime startTimestamp = getContentModel().getLastFedoraModificationDate();
checkLatestVersion();
// parse incomming XML
final StaxParser sp = new StaxParser();
// check optimistic locking criteria! and ID in root element?
sp.addHandler(new OptimisticLockingHandler(getContentModel().getId(), Constants.CONTENT_MODEL_OBJECT_TYPE,
getContentModel().getLastModificationDate()));
// get name and description
final ContentModelPropertiesHandler cmph = new ContentModelPropertiesHandler(sp);
sp.addHandler(cmph);
// get md-record definitions
final MdRecordDefinitionHandler mrdh =
new MdRecordDefinitionHandler(sp, "/content-model/md-record-definitions");
sp.addHandler(mrdh);
// get resource definitions
final ResourceDefinitionHandler rdh = new ResourceDefinitionHandler(sp, "/content-model/resource-definitions");
sp.addHandler(rdh);
// get content-streams
final ContentStreamsHandler csh = new ContentStreamsHandler(sp, "/content-model/content-streams");
sp.addHandler(csh);
try {
sp.parse(xmlData);
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final MissingAttributeValueException e) {
throw e;
}
catch (final InvalidXmlException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
+ catch (final OptimisticLockingException e) {
+ throw e;
+ }
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException(null, e);
}
final String description = getContentModel().getDescription() != null ? getContentModel().getDescription() : "";
if (!getContentModel().getTitle().equals(cmph.getProperties().getObjectProperties().getTitle())
|| !description.equals(cmph.getProperties().getObjectProperties().getDescription())) {
// update DC (title, description)
final Datastream dc = getContentModel().getDc();
final StaxParser dcParser = new StaxParser();
final TreeMap<String, StartElementWithText> updateElementsDc = new TreeMap<String, StartElementWithText>();
updateElementsDc.put(Elements.ELEMENT_DC_TITLE, new StartElementWithText(Elements.ELEMENT_DC_TITLE,
Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph.getProperties().getObjectProperties().getTitle(),
null));
updateElementsDc.put(Elements.ELEMENT_DC_DESCRIPTION, new StartElementWithText(
Elements.ELEMENT_DC_DESCRIPTION, Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph
.getProperties().getObjectProperties().getDescription(), null));
final DcUpdateHandler dcUpdateHandler = new DcUpdateHandler(updateElementsDc, dcParser);
dcParser.addHandler(dcUpdateHandler);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
final MultipleExtractor me = new MultipleExtractor(extractPathes, dcParser);
extractPathes.put("/dc", null);
dcParser.addHandler(me);
final byte[] dcNewBytes;
try {
dcParser.parse(dc.getStream());
final ByteArrayOutputStream dcUpdated = (ByteArrayOutputStream) me.getOutputStreams().get("dc");
dcNewBytes = dcUpdated.toByteArray();
}
catch (final Exception e) {
throw new XmlParserSystemException(e);
}
final String dcNew;
try {
dcNew = new String(dcNewBytes, XmlUtility.CHARACTER_ENCODING);
}
catch (final UnsupportedEncodingException e) {
throw new EncodingSystemException(e);
}
final Datastream newDs;
try {
newDs =
new Datastream("DC", getContentModel().getId(), dcNew.getBytes(XmlUtility.CHARACTER_ENCODING),
MimeTypes.TEXT_XML);
}
catch (final UnsupportedEncodingException e) {
throw new WebserverSystemException(e);
}
getContentModel().setDc(newDs);
}
final String sdexIdMidfix = getContentModel().getId().replaceAll(":", Constants.COLON_REPLACEMENT_PID) + '-';
final String sdefIdPrefix = "sdef:" + sdexIdMidfix;
// String sdepIdPrefix = "sdep:" + sdexIdMidfix;
final Map<String, ResourceDefinitionCreate> resourceDefinitions = rdh.getResourceDefinitions();
// update RELS-EXT
// FIXME store operation names in ContentModel and remove and add
// services in one pass or just remove if really gone
// delete service entries which are in Fedora but not send
final Map<String, List<StartElementWithChildElements>> deleteFromRelsExt =
new HashMap<String, List<StartElementWithChildElements>>();
final List<StartElementWithChildElements> deleteElementList = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : getContentModel().getResourceDefinitions().values()) {
if (!resourceDefinitions.containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements element =
new StartElementWithChildElements("hasService", Constants.FEDORA_MODEL_NS_URI, null, null, null,
null);
element.addAttribute(new Attribute("resource", Constants.RDF_NAMESPACE_URI, null, resourceDefinition
.getFedoraId(getContentModel().getId())));
deleteElementList.add(element);
}
}
deleteFromRelsExt.put("/RDF/Description/hasService", deleteElementList);
final byte[] tmpRelsExt = Utility.updateRelsExt(null, deleteFromRelsExt, null, getContentModel(), null);
// add services to RELS-EXT
final List<StartElementWithChildElements> addToRelsExt = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
// FIXME do update existing resource definitions
if (!getContentModel().getResourceDefinitions().containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements hasServiceElement = new StartElementWithChildElements();
hasServiceElement.setLocalName("hasService");
hasServiceElement.setPrefix(Constants.FEDORA_MODEL_NS_PREFIX);
hasServiceElement.setNamespace(Constants.FEDORA_MODEL_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX,
Constants.IDENTIFIER_PREFIX + sdefIdPrefix + resourceDefinition.getName());
hasServiceElement.addAttribute(resource);
addToRelsExt.add(hasServiceElement);
}
}
// TODO remove services from RELS-EXT
// (<hasService
// rdf:resource="info:fedora/sdef:escidoc_9003-trans"
// xmlns="info:fedora/fedora-system:def/model#"/>)
getContentModel().setRelsExt(Utility.updateRelsExt(addToRelsExt, null, tmpRelsExt, getContentModel(), null));
// Metadata Record Definitions
final List<MdRecordDefinitionCreate> mdRecordDefinitions = mrdh.getMdRecordDefinitions();
// update DS-COMPOSITE
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.put("MD_RECORDS", mdRecordDefinitions);
final String dsCompositeModelContent =
ContentModelFoXmlProvider.getInstance().getContentModelDsComposite(valueMap);
getContentModel().setDsCompositeModel(dsCompositeModelContent);
// TODO create, delete, update *_XSD datastreams
for (final MdRecordDefinitionCreate mdRecordDefinition : mdRecordDefinitions) {
final String name = mdRecordDefinition.getName();
final String xsdUrl = mdRecordDefinition.getSchemaHref();
getContentModel().setOtherStream(
name + "_xsd",
new Datastream(name + "_xsd", getContentModel().getId(), xsdUrl,
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED, MimeTypes.TEXT_XML));
}
// Resource Definitions
// services are already added to RELS-EXT
// TODO delete sdef+sdep
// create service definitions and deployments or update xslt
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
final String sdefId = sdefIdPrefix + resourceDefinition.getName();
if (this.tripleStoreUtility.exists(sdefId)) {
// check if href for xslt is changed
// /cmm/content-model/escidoc:40013/resource-\
// definitions/resource-definition/trans/xslt
if (resourceDefinition.getXsltHref().equalsIgnoreCase(
"/cmm/content-model/" + getContentModel().getId() + "/resource-definitions/resource-definition/"
+ resourceDefinition.getName() + "/xslt/content")) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Do not update xslt.");
}
}
else {
final ModifiyDatastreamPathParam path = new ModifiyDatastreamPathParam(sdefId, "xslt");
final ModifyDatastreamQueryParam query = new ModifyDatastreamQueryParam();
query.setDsLabel("Transformation instructions for operation '" + resourceDefinition.getName()
+ "'.");
query.setMimeType(MimeTypes.TEXT_XML);
query.setDsLocation(resourceDefinition.getXsltHref());
this.fedoraServiceClient.modifyDatastream(path, query, null);
}
}
else {
// create
final String sdefFoxml = getSDefFoXML(resourceDefinition);
final IngestPathParam path = new IngestPathParam();
final IngestQueryParam query = new IngestQueryParam();
this.fedoraServiceClient.ingest(path, query, sdefFoxml);
final String sdepFoxml = getSDepFoXML(resourceDefinition);
this.fedoraServiceClient.ingest(path, query, sdepFoxml);
}
}
// Content Streams
final List<ContentStreamCreate> contentStreams = csh.getContentStreams();
setContentStreams(contentStreams);
/*
*
*/
// check if modified
final String updatedXmlData;
final DateTime endTimestamp = getContentModel().getLastFedoraModificationDate();
if (!startTimestamp.isEqual(endTimestamp) || getContentModel().isNewVersion()) {
// object is modified
getUtility().makeVersion("ContentModelHandler.update()", null, getContentModel());
getContentModel().persist();
updatedXmlData = retrieve(getContentModel().getId());
fireContentModelModified(getContentModel().getId(), updatedXmlData);
}
else {
updatedXmlData = render();
}
return updatedXmlData;
}
/**
* Render service definition FoXML.
*
* @param resourceDefinition The resource definition create object.
* @return FoXML representation of service definition.
* @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
*/
private String getSDefFoXML(final ResourceDefinitionCreate resourceDefinition) throws WebserverSystemException {
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.putAll(getBehaviorValues(resourceDefinition));
return ContentModelFoXmlProvider.getInstance().getServiceDefinitionFoXml(valueMap);
}
/**
* Render service deployment FoXML.
*
* @param resourceDefinition The resource definition create object.
* @return FoXML representation of service deployment.
* @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
*/
private String getSDepFoXML(final ResourceDefinitionCreate resourceDefinition) throws WebserverSystemException {
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.putAll(getBehaviorValues(resourceDefinition));
return ContentModelFoXmlProvider.getInstance().getServiceDeploymentFoXml(valueMap);
}
private Map<String, Object> getBehaviorValues(final ResourceDefinitionCreate resourceDefinition) {
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.put(XmlTemplateProviderConstants.BEHAVIOR_CONTENT_MODEL_ID, getContentModel().getId());
valueMap.put(XmlTemplateProviderConstants.BEHAVIOR_CONTENT_MODEL_ID_UNDERSCORE, getContentModel()
.getId().replaceAll(":", Constants.COLON_REPLACEMENT_PID));
valueMap.put(XmlTemplateProviderConstants.BEHAVIOR_OPERATION_NAME, resourceDefinition.getName());
valueMap.put(XmlTemplateProviderConstants.BEHAVIOR_TRANSFORM_MD, resourceDefinition.getMdRecordName());
valueMap.put(XmlTemplateProviderConstants.BEHAVIOR_XSLT_HREF, resourceDefinition.getXsltHref());
return valueMap;
}
/**
* Creates Stream objects from the values in {@code contentStreamMap} and calls Item.setContentStreams with a
* HashMap which contains the metadata datastreams as Stream objects.
* @param contentStreams
* @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
* @throws de.escidoc.core.common.exceptions.system.FedoraSystemException
* @throws de.escidoc.core.common.exceptions.system.IntegritySystemException
*/
private void setContentStreams(final Iterable<ContentStreamCreate> contentStreams) throws WebserverSystemException,
IntegritySystemException, FedoraSystemException {
final Map<String, Datastream> contentStreamDatastreams = new HashMap<String, Datastream>();
for (final ContentStreamCreate contentStream : contentStreams) {
final String name = contentStream.getName();
final Datastream ds;
if (contentStream.getContent() != null && contentStream.getContent().getContent() != null) {
try {
ds =
new Datastream(name, getContentModel().getId(), contentStream
.getContent().getContent().getBytes(XmlUtility.CHARACTER_ENCODING), contentStream
.getMimeType());
}
catch (final UnsupportedEncodingException e) {
throw new WebserverSystemException(e);
}
}
else if (contentStream.getContent().getDataLocation() != null) {
ds =
new Datastream(name, getContentModel().getId(), contentStream
.getContent().getDataLocation().toString(), contentStream
.getContent().getStorageType().getESciDocName(), contentStream.getMimeType());
}
else {
throw new IntegritySystemException("Content streams has neither href nor content.");
}
String title = contentStream.getTitle();
if (title == null) {
title = "";
}
ds.setLabel(title.trim());
contentStreamDatastreams.put(name, ds);
}
getContentModel().setContentStreams(contentStreamDatastreams);
}
/**
* Check if the requested item version is the latest version.
*
* @throws ReadonlyVersionException If the requested item version is not the latest one.
*/
protected void checkLatestVersion() throws ReadonlyVersionException {
final String thisVersion = getContentModel().getVersionNumber();
if (thisVersion != null && !thisVersion.equals(getContentModel().getLatestVersionNumber())) {
throw new ReadonlyVersionException("Only latest version can be modified.");
}
}
/**
* Validate the Content Model structure in general (independent if create or ingest was selected).
* <p/>
* Checks if all required values are set and consistent.
*
* @param item The item which is to validate.
* @throws de.escidoc.core.common.exceptions.application.invalid.InvalidContentException
*/
private static void validate(final ContentModelCreate item) throws InvalidContentException {
// check public status of Content Model
final StatusType publicStatus = item.getProperties().getObjectProperties().getStatus();
if (publicStatus != StatusType.PENDING) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("New Content Model has to be in public-status '" + StatusType.PENDING + "'.");
}
item.getProperties().getObjectProperties().setStatus(StatusType.PENDING);
}
// validate Metadata Records
checkMetadataRecords(item);
}
/**
* Check if the name attribute of Metadata Records is unique and at least one Metadata Record has the name
* "escidoc".
*
* @param item Item which is to validate.
* @throws InvalidContentException Thrown if content is invalid.
*/
private static void checkMetadataRecords(final ContentModelCreate item) throws InvalidContentException {
final List<MdRecordCreate> mdRecords = item.getMetadataRecords();
if (!(mdRecords == null || mdRecords.size() < 1)) {
final Collection<String> mdRecordNames = new ArrayList<String>();
for (final MdRecordCreate mdRecord : mdRecords) {
final String name = mdRecord.getName();
// check uniqueness of names
if (mdRecordNames.contains(name)) {
throw new InvalidContentException("Metadata 'md-record' with name='" + name
+ "' exists multiple times.");
}
mdRecordNames.add(name);
}
}
}
/**
* @param xml
* @throws WebserverSystemException If an error occurs.
* @throws InvalidContentException If invalid content is found.
* @throws MissingAttributeValueException If a required attribute can not be found.
* @throws XmlParserSystemException If an unexpected error occurs while parsing.
* @throws XmlCorruptedException Thrown if the schema validation of the provided data failed.
* @return
*/
private static ContentModelCreate parseContentModel(final String xml) throws WebserverSystemException,
InvalidContentException, MissingAttributeValueException, XmlParserSystemException, XmlCorruptedException {
final StaxParser sp = new StaxParser();
final ContentModelCreateHandler contentModelHandler = new ContentModelCreateHandler(sp);
sp.addHandler(contentModelHandler);
try {
sp.parse(xml);
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final MissingAttributeValueException e) {
throw e;
}
catch (final XmlCorruptedException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException(null, e);
}
return contentModelHandler.getContentModel();
}
/**
* Check if the content model is locked.
*
* @throws WebserverSystemException Thrown in case of an internal error.
* @throws LockingException If the item is locked and the current user is not the one who locked it.
*/
protected void checkLocked() throws LockingException, WebserverSystemException {
if (getContentModel().isLocked() && !getContentModel().getLockOwner().equals(Utility.getCurrentUser()[0])) {
throw new LockingException("Content Model + " + getContentModel().getId() + " is locked by "
+ getContentModel().getLockOwner() + '.');
}
}
/**
* Set the SRURequest object.
*
* @param sruRequest SRURequest
*/
public void setSruRequest(final SRURequest sruRequest) {
this.sruRequest = sruRequest;
}
@Override
public String ingest(final String xmlData) throws InvalidContentException, MissingAttributeValueException,
SystemException, XmlCorruptedException {
final ContentModelCreate cm = parseContentModel(xmlData);
cm.setIdProvider(getIdProvider());
validate(cm);
cm.persist(true);
final String objid = cm.getObjid();
try {
if (EscidocConfiguration.getInstance().getAsBoolean(
EscidocConfiguration.ESCIDOC_CORE_NOTIFY_INDEXER_ENABLED)) {
fireContentModelCreated(objid, retrieve(objid));
}
}
catch (final ResourceNotFoundException e) {
throw new IntegritySystemException("The Content Model with id '" + objid + "', which was just ingested, "
+ "could not be found for retrieve.", e);
}
return objid;
}
/**
* Notify the listeners that a Content Model was modified.
*
* @param id Content Model id
* @param xmlData complete Content Model XML
* @throws SystemException One of the listeners threw an exception.
*/
private void fireContentModelModified(final String id, final String xmlData) throws SystemException {
for (final ResourceListener contentModelListener : this.contentModelListeners) {
contentModelListener.resourceModified(id, xmlData);
}
}
/**
* Notify the listeners that an Content Model was created.
*
* @param id Content Model id
* @param xmlData complete Content Model XML
* @throws SystemException One of the listeners threw an exception.
*/
private void fireContentModelCreated(final String id, final String xmlData) throws SystemException {
for (final ResourceListener contentModelListener : this.contentModelListeners) {
contentModelListener.resourceCreated(id, xmlData);
}
}
/**
* Notify the listeners that an Content Model was deleted.
*
* @param id Content Model id
* @throws SystemException One of the listeners threw an exception.
*/
private void fireContentModelDeleted(final String id) throws SystemException {
for (final ResourceListener contentModelListener : this.contentModelListeners) {
contentModelListener.resourceDeleted(id);
}
}
}
| true | true | public String update(final String id, final String xmlData) throws ContentModelNotFoundException,
OptimisticLockingException, SystemException, ReadonlyVersionException, MissingAttributeValueException,
InvalidXmlException, InvalidContentException {
setContentModel(id);
final DateTime startTimestamp = getContentModel().getLastFedoraModificationDate();
checkLatestVersion();
// parse incomming XML
final StaxParser sp = new StaxParser();
// check optimistic locking criteria! and ID in root element?
sp.addHandler(new OptimisticLockingHandler(getContentModel().getId(), Constants.CONTENT_MODEL_OBJECT_TYPE,
getContentModel().getLastModificationDate()));
// get name and description
final ContentModelPropertiesHandler cmph = new ContentModelPropertiesHandler(sp);
sp.addHandler(cmph);
// get md-record definitions
final MdRecordDefinitionHandler mrdh =
new MdRecordDefinitionHandler(sp, "/content-model/md-record-definitions");
sp.addHandler(mrdh);
// get resource definitions
final ResourceDefinitionHandler rdh = new ResourceDefinitionHandler(sp, "/content-model/resource-definitions");
sp.addHandler(rdh);
// get content-streams
final ContentStreamsHandler csh = new ContentStreamsHandler(sp, "/content-model/content-streams");
sp.addHandler(csh);
try {
sp.parse(xmlData);
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final MissingAttributeValueException e) {
throw e;
}
catch (final InvalidXmlException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException(null, e);
}
final String description = getContentModel().getDescription() != null ? getContentModel().getDescription() : "";
if (!getContentModel().getTitle().equals(cmph.getProperties().getObjectProperties().getTitle())
|| !description.equals(cmph.getProperties().getObjectProperties().getDescription())) {
// update DC (title, description)
final Datastream dc = getContentModel().getDc();
final StaxParser dcParser = new StaxParser();
final TreeMap<String, StartElementWithText> updateElementsDc = new TreeMap<String, StartElementWithText>();
updateElementsDc.put(Elements.ELEMENT_DC_TITLE, new StartElementWithText(Elements.ELEMENT_DC_TITLE,
Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph.getProperties().getObjectProperties().getTitle(),
null));
updateElementsDc.put(Elements.ELEMENT_DC_DESCRIPTION, new StartElementWithText(
Elements.ELEMENT_DC_DESCRIPTION, Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph
.getProperties().getObjectProperties().getDescription(), null));
final DcUpdateHandler dcUpdateHandler = new DcUpdateHandler(updateElementsDc, dcParser);
dcParser.addHandler(dcUpdateHandler);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
final MultipleExtractor me = new MultipleExtractor(extractPathes, dcParser);
extractPathes.put("/dc", null);
dcParser.addHandler(me);
final byte[] dcNewBytes;
try {
dcParser.parse(dc.getStream());
final ByteArrayOutputStream dcUpdated = (ByteArrayOutputStream) me.getOutputStreams().get("dc");
dcNewBytes = dcUpdated.toByteArray();
}
catch (final Exception e) {
throw new XmlParserSystemException(e);
}
final String dcNew;
try {
dcNew = new String(dcNewBytes, XmlUtility.CHARACTER_ENCODING);
}
catch (final UnsupportedEncodingException e) {
throw new EncodingSystemException(e);
}
final Datastream newDs;
try {
newDs =
new Datastream("DC", getContentModel().getId(), dcNew.getBytes(XmlUtility.CHARACTER_ENCODING),
MimeTypes.TEXT_XML);
}
catch (final UnsupportedEncodingException e) {
throw new WebserverSystemException(e);
}
getContentModel().setDc(newDs);
}
final String sdexIdMidfix = getContentModel().getId().replaceAll(":", Constants.COLON_REPLACEMENT_PID) + '-';
final String sdefIdPrefix = "sdef:" + sdexIdMidfix;
// String sdepIdPrefix = "sdep:" + sdexIdMidfix;
final Map<String, ResourceDefinitionCreate> resourceDefinitions = rdh.getResourceDefinitions();
// update RELS-EXT
// FIXME store operation names in ContentModel and remove and add
// services in one pass or just remove if really gone
// delete service entries which are in Fedora but not send
final Map<String, List<StartElementWithChildElements>> deleteFromRelsExt =
new HashMap<String, List<StartElementWithChildElements>>();
final List<StartElementWithChildElements> deleteElementList = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : getContentModel().getResourceDefinitions().values()) {
if (!resourceDefinitions.containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements element =
new StartElementWithChildElements("hasService", Constants.FEDORA_MODEL_NS_URI, null, null, null,
null);
element.addAttribute(new Attribute("resource", Constants.RDF_NAMESPACE_URI, null, resourceDefinition
.getFedoraId(getContentModel().getId())));
deleteElementList.add(element);
}
}
deleteFromRelsExt.put("/RDF/Description/hasService", deleteElementList);
final byte[] tmpRelsExt = Utility.updateRelsExt(null, deleteFromRelsExt, null, getContentModel(), null);
// add services to RELS-EXT
final List<StartElementWithChildElements> addToRelsExt = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
// FIXME do update existing resource definitions
if (!getContentModel().getResourceDefinitions().containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements hasServiceElement = new StartElementWithChildElements();
hasServiceElement.setLocalName("hasService");
hasServiceElement.setPrefix(Constants.FEDORA_MODEL_NS_PREFIX);
hasServiceElement.setNamespace(Constants.FEDORA_MODEL_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX,
Constants.IDENTIFIER_PREFIX + sdefIdPrefix + resourceDefinition.getName());
hasServiceElement.addAttribute(resource);
addToRelsExt.add(hasServiceElement);
}
}
// TODO remove services from RELS-EXT
// (<hasService
// rdf:resource="info:fedora/sdef:escidoc_9003-trans"
// xmlns="info:fedora/fedora-system:def/model#"/>)
getContentModel().setRelsExt(Utility.updateRelsExt(addToRelsExt, null, tmpRelsExt, getContentModel(), null));
// Metadata Record Definitions
final List<MdRecordDefinitionCreate> mdRecordDefinitions = mrdh.getMdRecordDefinitions();
// update DS-COMPOSITE
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.put("MD_RECORDS", mdRecordDefinitions);
final String dsCompositeModelContent =
ContentModelFoXmlProvider.getInstance().getContentModelDsComposite(valueMap);
getContentModel().setDsCompositeModel(dsCompositeModelContent);
// TODO create, delete, update *_XSD datastreams
for (final MdRecordDefinitionCreate mdRecordDefinition : mdRecordDefinitions) {
final String name = mdRecordDefinition.getName();
final String xsdUrl = mdRecordDefinition.getSchemaHref();
getContentModel().setOtherStream(
name + "_xsd",
new Datastream(name + "_xsd", getContentModel().getId(), xsdUrl,
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED, MimeTypes.TEXT_XML));
}
// Resource Definitions
// services are already added to RELS-EXT
// TODO delete sdef+sdep
// create service definitions and deployments or update xslt
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
final String sdefId = sdefIdPrefix + resourceDefinition.getName();
if (this.tripleStoreUtility.exists(sdefId)) {
// check if href for xslt is changed
// /cmm/content-model/escidoc:40013/resource-\
// definitions/resource-definition/trans/xslt
if (resourceDefinition.getXsltHref().equalsIgnoreCase(
"/cmm/content-model/" + getContentModel().getId() + "/resource-definitions/resource-definition/"
+ resourceDefinition.getName() + "/xslt/content")) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Do not update xslt.");
}
}
else {
final ModifiyDatastreamPathParam path = new ModifiyDatastreamPathParam(sdefId, "xslt");
final ModifyDatastreamQueryParam query = new ModifyDatastreamQueryParam();
query.setDsLabel("Transformation instructions for operation '" + resourceDefinition.getName()
+ "'.");
query.setMimeType(MimeTypes.TEXT_XML);
query.setDsLocation(resourceDefinition.getXsltHref());
this.fedoraServiceClient.modifyDatastream(path, query, null);
}
}
else {
// create
final String sdefFoxml = getSDefFoXML(resourceDefinition);
final IngestPathParam path = new IngestPathParam();
final IngestQueryParam query = new IngestQueryParam();
this.fedoraServiceClient.ingest(path, query, sdefFoxml);
final String sdepFoxml = getSDepFoXML(resourceDefinition);
this.fedoraServiceClient.ingest(path, query, sdepFoxml);
}
}
// Content Streams
final List<ContentStreamCreate> contentStreams = csh.getContentStreams();
setContentStreams(contentStreams);
/*
*
*/
// check if modified
final String updatedXmlData;
final DateTime endTimestamp = getContentModel().getLastFedoraModificationDate();
if (!startTimestamp.isEqual(endTimestamp) || getContentModel().isNewVersion()) {
// object is modified
getUtility().makeVersion("ContentModelHandler.update()", null, getContentModel());
getContentModel().persist();
updatedXmlData = retrieve(getContentModel().getId());
fireContentModelModified(getContentModel().getId(), updatedXmlData);
}
else {
updatedXmlData = render();
}
return updatedXmlData;
}
| public String update(final String id, final String xmlData) throws ContentModelNotFoundException,
OptimisticLockingException, SystemException, ReadonlyVersionException, MissingAttributeValueException,
InvalidXmlException, InvalidContentException {
setContentModel(id);
final DateTime startTimestamp = getContentModel().getLastFedoraModificationDate();
checkLatestVersion();
// parse incomming XML
final StaxParser sp = new StaxParser();
// check optimistic locking criteria! and ID in root element?
sp.addHandler(new OptimisticLockingHandler(getContentModel().getId(), Constants.CONTENT_MODEL_OBJECT_TYPE,
getContentModel().getLastModificationDate()));
// get name and description
final ContentModelPropertiesHandler cmph = new ContentModelPropertiesHandler(sp);
sp.addHandler(cmph);
// get md-record definitions
final MdRecordDefinitionHandler mrdh =
new MdRecordDefinitionHandler(sp, "/content-model/md-record-definitions");
sp.addHandler(mrdh);
// get resource definitions
final ResourceDefinitionHandler rdh = new ResourceDefinitionHandler(sp, "/content-model/resource-definitions");
sp.addHandler(rdh);
// get content-streams
final ContentStreamsHandler csh = new ContentStreamsHandler(sp, "/content-model/content-streams");
sp.addHandler(csh);
try {
sp.parse(xmlData);
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final MissingAttributeValueException e) {
throw e;
}
catch (final InvalidXmlException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final OptimisticLockingException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException(null, e);
}
final String description = getContentModel().getDescription() != null ? getContentModel().getDescription() : "";
if (!getContentModel().getTitle().equals(cmph.getProperties().getObjectProperties().getTitle())
|| !description.equals(cmph.getProperties().getObjectProperties().getDescription())) {
// update DC (title, description)
final Datastream dc = getContentModel().getDc();
final StaxParser dcParser = new StaxParser();
final TreeMap<String, StartElementWithText> updateElementsDc = new TreeMap<String, StartElementWithText>();
updateElementsDc.put(Elements.ELEMENT_DC_TITLE, new StartElementWithText(Elements.ELEMENT_DC_TITLE,
Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph.getProperties().getObjectProperties().getTitle(),
null));
updateElementsDc.put(Elements.ELEMENT_DC_DESCRIPTION, new StartElementWithText(
Elements.ELEMENT_DC_DESCRIPTION, Constants.DC_NS_URI, Constants.DC_NS_PREFIX, cmph
.getProperties().getObjectProperties().getDescription(), null));
final DcUpdateHandler dcUpdateHandler = new DcUpdateHandler(updateElementsDc, dcParser);
dcParser.addHandler(dcUpdateHandler);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
final MultipleExtractor me = new MultipleExtractor(extractPathes, dcParser);
extractPathes.put("/dc", null);
dcParser.addHandler(me);
final byte[] dcNewBytes;
try {
dcParser.parse(dc.getStream());
final ByteArrayOutputStream dcUpdated = (ByteArrayOutputStream) me.getOutputStreams().get("dc");
dcNewBytes = dcUpdated.toByteArray();
}
catch (final Exception e) {
throw new XmlParserSystemException(e);
}
final String dcNew;
try {
dcNew = new String(dcNewBytes, XmlUtility.CHARACTER_ENCODING);
}
catch (final UnsupportedEncodingException e) {
throw new EncodingSystemException(e);
}
final Datastream newDs;
try {
newDs =
new Datastream("DC", getContentModel().getId(), dcNew.getBytes(XmlUtility.CHARACTER_ENCODING),
MimeTypes.TEXT_XML);
}
catch (final UnsupportedEncodingException e) {
throw new WebserverSystemException(e);
}
getContentModel().setDc(newDs);
}
final String sdexIdMidfix = getContentModel().getId().replaceAll(":", Constants.COLON_REPLACEMENT_PID) + '-';
final String sdefIdPrefix = "sdef:" + sdexIdMidfix;
// String sdepIdPrefix = "sdep:" + sdexIdMidfix;
final Map<String, ResourceDefinitionCreate> resourceDefinitions = rdh.getResourceDefinitions();
// update RELS-EXT
// FIXME store operation names in ContentModel and remove and add
// services in one pass or just remove if really gone
// delete service entries which are in Fedora but not send
final Map<String, List<StartElementWithChildElements>> deleteFromRelsExt =
new HashMap<String, List<StartElementWithChildElements>>();
final List<StartElementWithChildElements> deleteElementList = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : getContentModel().getResourceDefinitions().values()) {
if (!resourceDefinitions.containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements element =
new StartElementWithChildElements("hasService", Constants.FEDORA_MODEL_NS_URI, null, null, null,
null);
element.addAttribute(new Attribute("resource", Constants.RDF_NAMESPACE_URI, null, resourceDefinition
.getFedoraId(getContentModel().getId())));
deleteElementList.add(element);
}
}
deleteFromRelsExt.put("/RDF/Description/hasService", deleteElementList);
final byte[] tmpRelsExt = Utility.updateRelsExt(null, deleteFromRelsExt, null, getContentModel(), null);
// add services to RELS-EXT
final List<StartElementWithChildElements> addToRelsExt = new ArrayList<StartElementWithChildElements>();
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
// FIXME do update existing resource definitions
if (!getContentModel().getResourceDefinitions().containsKey(resourceDefinition.getName())) {
final StartElementWithChildElements hasServiceElement = new StartElementWithChildElements();
hasServiceElement.setLocalName("hasService");
hasServiceElement.setPrefix(Constants.FEDORA_MODEL_NS_PREFIX);
hasServiceElement.setNamespace(Constants.FEDORA_MODEL_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX,
Constants.IDENTIFIER_PREFIX + sdefIdPrefix + resourceDefinition.getName());
hasServiceElement.addAttribute(resource);
addToRelsExt.add(hasServiceElement);
}
}
// TODO remove services from RELS-EXT
// (<hasService
// rdf:resource="info:fedora/sdef:escidoc_9003-trans"
// xmlns="info:fedora/fedora-system:def/model#"/>)
getContentModel().setRelsExt(Utility.updateRelsExt(addToRelsExt, null, tmpRelsExt, getContentModel(), null));
// Metadata Record Definitions
final List<MdRecordDefinitionCreate> mdRecordDefinitions = mrdh.getMdRecordDefinitions();
// update DS-COMPOSITE
final Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.put("MD_RECORDS", mdRecordDefinitions);
final String dsCompositeModelContent =
ContentModelFoXmlProvider.getInstance().getContentModelDsComposite(valueMap);
getContentModel().setDsCompositeModel(dsCompositeModelContent);
// TODO create, delete, update *_XSD datastreams
for (final MdRecordDefinitionCreate mdRecordDefinition : mdRecordDefinitions) {
final String name = mdRecordDefinition.getName();
final String xsdUrl = mdRecordDefinition.getSchemaHref();
getContentModel().setOtherStream(
name + "_xsd",
new Datastream(name + "_xsd", getContentModel().getId(), xsdUrl,
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED, MimeTypes.TEXT_XML));
}
// Resource Definitions
// services are already added to RELS-EXT
// TODO delete sdef+sdep
// create service definitions and deployments or update xslt
for (final ResourceDefinitionCreate resourceDefinition : resourceDefinitions.values()) {
final String sdefId = sdefIdPrefix + resourceDefinition.getName();
if (this.tripleStoreUtility.exists(sdefId)) {
// check if href for xslt is changed
// /cmm/content-model/escidoc:40013/resource-\
// definitions/resource-definition/trans/xslt
if (resourceDefinition.getXsltHref().equalsIgnoreCase(
"/cmm/content-model/" + getContentModel().getId() + "/resource-definitions/resource-definition/"
+ resourceDefinition.getName() + "/xslt/content")) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Do not update xslt.");
}
}
else {
final ModifiyDatastreamPathParam path = new ModifiyDatastreamPathParam(sdefId, "xslt");
final ModifyDatastreamQueryParam query = new ModifyDatastreamQueryParam();
query.setDsLabel("Transformation instructions for operation '" + resourceDefinition.getName()
+ "'.");
query.setMimeType(MimeTypes.TEXT_XML);
query.setDsLocation(resourceDefinition.getXsltHref());
this.fedoraServiceClient.modifyDatastream(path, query, null);
}
}
else {
// create
final String sdefFoxml = getSDefFoXML(resourceDefinition);
final IngestPathParam path = new IngestPathParam();
final IngestQueryParam query = new IngestQueryParam();
this.fedoraServiceClient.ingest(path, query, sdefFoxml);
final String sdepFoxml = getSDepFoXML(resourceDefinition);
this.fedoraServiceClient.ingest(path, query, sdepFoxml);
}
}
// Content Streams
final List<ContentStreamCreate> contentStreams = csh.getContentStreams();
setContentStreams(contentStreams);
/*
*
*/
// check if modified
final String updatedXmlData;
final DateTime endTimestamp = getContentModel().getLastFedoraModificationDate();
if (!startTimestamp.isEqual(endTimestamp) || getContentModel().isNewVersion()) {
// object is modified
getUtility().makeVersion("ContentModelHandler.update()", null, getContentModel());
getContentModel().persist();
updatedXmlData = retrieve(getContentModel().getId());
fireContentModelModified(getContentModel().getId(), updatedXmlData);
}
else {
updatedXmlData = render();
}
return updatedXmlData;
}
|
diff --git a/code/server/app/controllers/C2DM.java b/code/server/app/controllers/C2DM.java
index 513d7b3..62b430c 100644
--- a/code/server/app/controllers/C2DM.java
+++ b/code/server/app/controllers/C2DM.java
@@ -1,65 +1,69 @@
package controllers;
import com.google.gson.JsonArray;
import models.Transaction;
import models.User;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import play.Play;
import play.libs.WS;
import play.mvc.Controller;
import utils.GsonUtil;
import utils.ModelHelper;
import java.util.ArrayList;
import java.util.List;
public class C2DM extends Controller {
private static Logger logger = Logger.getLogger(
C2DM.class.getName());
private static final String C2DM_PUSH_TOKEN = Play.configuration.
getProperty("c2dm.push.token");
private static final String C2DM_PUSH_URL = Play.configuration.
getProperty("c2dm.push.url");
public static void c2dm(String registrationId, JsonArray json) {
if (C2DM_PUSH_TOKEN == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.token i application.conf");
return;
}
if (C2DM_PUSH_URL == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.url i application.conf");
return;
}
final List<Transaction> transactions = GsonUtil.parseTransactions(json);
final List<Transaction> updated = new ArrayList<Transaction>();
final User user = User.find("deviceId", registrationId).first();
if (user == null) {
logger.log(Level.ERROR, "No user found with deviceId: " + registrationId);
return;
}
+ if (transactions == null) {
+ logger.log(Level.ERROR, "No transactions found with deviceId: " + registrationId);
+ return;
+ }
for (Transaction t : transactions) {
updated.add(ModelHelper.saveOrUpdate(t, user));
}
if (updated.isEmpty()) {
logger.log(Level.ERROR,
"No transactions were saved");
return;
}
WS.WSRequest request = WS.url(C2DM_PUSH_URL);
request.headers.put("Authorization", String.format(
"GoogleLogin auth=%s", C2DM_PUSH_TOKEN));
request.parameters.put("registration_id", registrationId);
request.parameters.put("data.message", updated.size());
request.parameters.put("collapse_key", ",");
WS.HttpResponse response = request.post();
if (response.getStatus() != 200) {
logger.log(Level.ERROR, "Failed to send C2DM message: " +
response.getString());
}
}
}
| true | true | public static void c2dm(String registrationId, JsonArray json) {
if (C2DM_PUSH_TOKEN == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.token i application.conf");
return;
}
if (C2DM_PUSH_URL == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.url i application.conf");
return;
}
final List<Transaction> transactions = GsonUtil.parseTransactions(json);
final List<Transaction> updated = new ArrayList<Transaction>();
final User user = User.find("deviceId", registrationId).first();
if (user == null) {
logger.log(Level.ERROR, "No user found with deviceId: " + registrationId);
return;
}
for (Transaction t : transactions) {
updated.add(ModelHelper.saveOrUpdate(t, user));
}
if (updated.isEmpty()) {
logger.log(Level.ERROR,
"No transactions were saved");
return;
}
WS.WSRequest request = WS.url(C2DM_PUSH_URL);
request.headers.put("Authorization", String.format(
"GoogleLogin auth=%s", C2DM_PUSH_TOKEN));
request.parameters.put("registration_id", registrationId);
request.parameters.put("data.message", updated.size());
request.parameters.put("collapse_key", ",");
WS.HttpResponse response = request.post();
if (response.getStatus() != 200) {
logger.log(Level.ERROR, "Failed to send C2DM message: " +
response.getString());
}
}
| public static void c2dm(String registrationId, JsonArray json) {
if (C2DM_PUSH_TOKEN == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.token i application.conf");
return;
}
if (C2DM_PUSH_URL == null) {
logger.log(Level.ERROR,
"Missing c2dm.push.url i application.conf");
return;
}
final List<Transaction> transactions = GsonUtil.parseTransactions(json);
final List<Transaction> updated = new ArrayList<Transaction>();
final User user = User.find("deviceId", registrationId).first();
if (user == null) {
logger.log(Level.ERROR, "No user found with deviceId: " + registrationId);
return;
}
if (transactions == null) {
logger.log(Level.ERROR, "No transactions found with deviceId: " + registrationId);
return;
}
for (Transaction t : transactions) {
updated.add(ModelHelper.saveOrUpdate(t, user));
}
if (updated.isEmpty()) {
logger.log(Level.ERROR,
"No transactions were saved");
return;
}
WS.WSRequest request = WS.url(C2DM_PUSH_URL);
request.headers.put("Authorization", String.format(
"GoogleLogin auth=%s", C2DM_PUSH_TOKEN));
request.parameters.put("registration_id", registrationId);
request.parameters.put("data.message", updated.size());
request.parameters.put("collapse_key", ",");
WS.HttpResponse response = request.post();
if (response.getStatus() != 200) {
logger.log(Level.ERROR, "Failed to send C2DM message: " +
response.getString());
}
}
|
diff --git a/cat-consumer/src/test/java/com/dianping/cat/consumer/impl/OneAnalyzerTwoDurationTest.java b/cat-consumer/src/test/java/com/dianping/cat/consumer/impl/OneAnalyzerTwoDurationTest.java
index 80067425..ad1d2353 100644
--- a/cat-consumer/src/test/java/com/dianping/cat/consumer/impl/OneAnalyzerTwoDurationTest.java
+++ b/cat-consumer/src/test/java/com/dianping/cat/consumer/impl/OneAnalyzerTwoDurationTest.java
@@ -1,108 +1,106 @@
package com.dianping.cat.consumer.impl;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.dianping.cat.message.internal.AbstractMessage;
import com.dianping.cat.message.spi.AbstractMessageAnalyzer;
import com.dianping.cat.message.spi.MessageConsumer;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;
import com.site.lookup.ComponentTestCase;
/**
* The tree message is in the latest two hours
*
* @author yong.you
*
*/
@RunWith(JUnit4.class)
public class OneAnalyzerTwoDurationTest extends ComponentTestCase {
private static int s_count1;
private static int s_count2;
private static int s_period = 0;
@Test
public void test() throws Exception {
MessageConsumer consumer = lookup(MessageConsumer.class, "mock");
- // һ��Сʱǰ��Message
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(-1));
consumer.consume(tree);
}
- // ��ǰһ��Сʱ��Message
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(1));
consumer.consume(tree);
}
Thread.sleep(1000 * 2);
Assert.assertEquals(100, s_count1);
Assert.assertEquals(200, s_count2);
Assert.assertEquals(2, s_period);
}
public static class MockAnalyzer extends
AbstractMessageAnalyzer<AnalyzerResult> {
public MockAnalyzer() {
s_period++;
}
@Override
protected void store(AnalyzerResult result) {
}
@Override
public AnalyzerResult generate() {
return null;
}
@Override
protected void process(MessageTree tree) {
long time = tree.getMessage().getTimestamp();
long systemTime = System.currentTimeMillis();
if (systemTime - time > 30 * 60 * 1000)
s_count1++;
else
s_count2 = s_count2 + 2;
}
@Override
protected boolean isTimeout() {
// TODO Auto-generated method stub
return false;
}
}
public static class AnalyzerResult {
}
static class MockMessage extends AbstractMessage {
private int type;
public MockMessage(int type) {
super(null, null);
this.type = type;
}
@Override
public long getTimestamp() {
if (type == -1)
return System.currentTimeMillis() - 60 * 60 * 1000;
return System.currentTimeMillis();
}
@Override
public void complete() {
}
}
}
| false | true | public void test() throws Exception {
MessageConsumer consumer = lookup(MessageConsumer.class, "mock");
// һ��Сʱǰ��Message
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(-1));
consumer.consume(tree);
}
// ��ǰһ��Сʱ��Message
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(1));
consumer.consume(tree);
}
Thread.sleep(1000 * 2);
Assert.assertEquals(100, s_count1);
Assert.assertEquals(200, s_count2);
Assert.assertEquals(2, s_period);
}
| public void test() throws Exception {
MessageConsumer consumer = lookup(MessageConsumer.class, "mock");
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(-1));
consumer.consume(tree);
}
for (int i = 0; i < 100; i++) {
DefaultMessageTree tree = new DefaultMessageTree();
tree.setMessage(new MockMessage(1));
consumer.consume(tree);
}
Thread.sleep(1000 * 2);
Assert.assertEquals(100, s_count1);
Assert.assertEquals(200, s_count2);
Assert.assertEquals(2, s_period);
}
|
diff --git a/libs/lib.algorithm/src/main/java/guibin/zhang/leecode/permutationAndCombination/ThreeSumCloset.java b/libs/lib.algorithm/src/main/java/guibin/zhang/leecode/permutationAndCombination/ThreeSumCloset.java
index 494aa93..4ce3072 100644
--- a/libs/lib.algorithm/src/main/java/guibin/zhang/leecode/permutationAndCombination/ThreeSumCloset.java
+++ b/libs/lib.algorithm/src/main/java/guibin/zhang/leecode/permutationAndCombination/ThreeSumCloset.java
@@ -1,49 +1,50 @@
package guibin.zhang.leecode.permutationAndCombination;
import java.util.Arrays;
/**
*
*
*
* @author Gubin Zhang <[email protected]>
*/
public class ThreeSumCloset {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = num.length;
if(len < 3) return 0;
- int closet = num[0];
+ int closet = num[0] + num[1] + num[2];
Arrays.sort(num);
for (int i = 0; i < len - 2; i++) {
int j = i + 1;
int m = len - 1;
while (j < m) {
- int delta = num[i] + num[j] + num[m] - target;
+ int sum = num[i] + num[j] + num[m];
+ int delta = sum - target;
if (delta == 0) {
- closet = delta;
+ closet = sum;
return closet;
} else {
- if (Math.abs(delta) < Math.abs(closet)) {
- closet = delta;
+ if (Math.abs(delta) < Math.abs(closet - target)) {
+ closet = sum;
}
if (delta > 0) {
m --;
} else {
j ++;
}
}
}
}
return closet;
}
public static void main(String[] args) {
ThreeSumCloset ts = new ThreeSumCloset();
int[] num = {0, 0, 0};
System.out.println(ts.threeSumClosest(num, 1));
}
}
| false | true | public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = num.length;
if(len < 3) return 0;
int closet = num[0];
Arrays.sort(num);
for (int i = 0; i < len - 2; i++) {
int j = i + 1;
int m = len - 1;
while (j < m) {
int delta = num[i] + num[j] + num[m] - target;
if (delta == 0) {
closet = delta;
return closet;
} else {
if (Math.abs(delta) < Math.abs(closet)) {
closet = delta;
}
if (delta > 0) {
m --;
} else {
j ++;
}
}
}
}
return closet;
}
| public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = num.length;
if(len < 3) return 0;
int closet = num[0] + num[1] + num[2];
Arrays.sort(num);
for (int i = 0; i < len - 2; i++) {
int j = i + 1;
int m = len - 1;
while (j < m) {
int sum = num[i] + num[j] + num[m];
int delta = sum - target;
if (delta == 0) {
closet = sum;
return closet;
} else {
if (Math.abs(delta) < Math.abs(closet - target)) {
closet = sum;
}
if (delta > 0) {
m --;
} else {
j ++;
}
}
}
}
return closet;
}
|
diff --git a/src/net/evendanan/pushingpixels/ListPreference.java b/src/net/evendanan/pushingpixels/ListPreference.java
index 352bc2c..04de5c5 100644
--- a/src/net/evendanan/pushingpixels/ListPreference.java
+++ b/src/net/evendanan/pushingpixels/ListPreference.java
@@ -1,57 +1,61 @@
/*
* Copyright (c) 2013 Menny Even-Danan
*
* 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.evendanan.pushingpixels;
import android.content.Context;
import android.util.AttributeSet;
/**
* The same as the regular ListPreference, but allows formatting of the summary field.
* This is not needed if your min-API is Honeycomb (since it's there already).
*/
public class ListPreference extends android.preference.ListPreference {
public ListPreference(Context context) {
super(context);
}
public ListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public CharSequence getSummary() {
//I need to update the summary, in case it includes a String#Format place-holders.
//now, what does this code do: In some versions of Android (prior to Honeycomb)
//the getSummary does include the nifty trick of allowing the developer to
//use the %s place holder. So, if I include a "%s" in the strings, in Gingerbread it will be printed
//while in Honeycomb it will be replaced with the current selection.
//So I hack: If the device is GB, then "getSummary" will include the %s, and the String.format function
//will replace it. Win!
//if the device is Honeycomb, then "getSummary" will already replace the %s, and it wont be there, and
//the String.format function will do nothing! Win again!
- return String.format(super.getSummary().toString(), getEntry());
+ final CharSequence baseSummary = super.getSummary();
+ if (TextUtils.isEmpty(baseSummary))//baseSummary may be null
+ return baseSummary;
+ else
+ return String.format(baseSummary.toString(), getEntry());
}
@Override
public void setValue(String value) {
super.setValue(value);
//so the Summary will be updated
notifyChanged();
}
}
| true | true | public CharSequence getSummary() {
//I need to update the summary, in case it includes a String#Format place-holders.
//now, what does this code do: In some versions of Android (prior to Honeycomb)
//the getSummary does include the nifty trick of allowing the developer to
//use the %s place holder. So, if I include a "%s" in the strings, in Gingerbread it will be printed
//while in Honeycomb it will be replaced with the current selection.
//So I hack: If the device is GB, then "getSummary" will include the %s, and the String.format function
//will replace it. Win!
//if the device is Honeycomb, then "getSummary" will already replace the %s, and it wont be there, and
//the String.format function will do nothing! Win again!
return String.format(super.getSummary().toString(), getEntry());
}
| public CharSequence getSummary() {
//I need to update the summary, in case it includes a String#Format place-holders.
//now, what does this code do: In some versions of Android (prior to Honeycomb)
//the getSummary does include the nifty trick of allowing the developer to
//use the %s place holder. So, if I include a "%s" in the strings, in Gingerbread it will be printed
//while in Honeycomb it will be replaced with the current selection.
//So I hack: If the device is GB, then "getSummary" will include the %s, and the String.format function
//will replace it. Win!
//if the device is Honeycomb, then "getSummary" will already replace the %s, and it wont be there, and
//the String.format function will do nothing! Win again!
final CharSequence baseSummary = super.getSummary();
if (TextUtils.isEmpty(baseSummary))//baseSummary may be null
return baseSummary;
else
return String.format(baseSummary.toString(), getEntry());
}
|
diff --git a/bombermen2/bombermen/src/pt/up/fe/pt/lpoo/bombermen/MapLoader.java b/bombermen2/bombermen/src/pt/up/fe/pt/lpoo/bombermen/MapLoader.java
index 341de29..16dd586 100644
--- a/bombermen2/bombermen/src/pt/up/fe/pt/lpoo/bombermen/MapLoader.java
+++ b/bombermen2/bombermen/src/pt/up/fe/pt/lpoo/bombermen/MapLoader.java
@@ -1,66 +1,66 @@
package pt.up.fe.pt.lpoo.bombermen;
import pt.up.fe.pt.lpoo.utils.Ref;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.MathUtils;
/* VERY IMPORTANT _lastGuid IS JUST AN HACK */
public class MapLoader
{
private int _lastGuid = 100;
public MapLoader(World w, EntityBuilder entB)
{
_world = w;
_entityBuilder = entB;
}
public boolean TryLoad(int number, Ref<Integer> width, Ref<Integer> height)
{
FileHandle file = Gdx.files.internal("data/map" + number + ".txt");
if (!file.exists()) return false;
if (file.isDirectory()) return false;
String str = file.readString(Constants.DEFAULT_MAP_FILE_CHARSET);
String lines[] = str.split("\\r?\\n");
for (int y = 0; y < lines.length; ++y)
{
char[] chars = lines[y].toCharArray();
for (int x = 0; x < chars.length; ++x)
{
switch (chars[x])
{
case ' ': // empty space, can be destroyable wall
- if (MathUtils.random() < Constants.WALL_CHANCE) AddWall(1, x, y);
+ if (MathUtils.random() < Constants.WALL_CHANCE) AddWall(1, x, lines.length - 1 - y);
break;
case 'X': // undestroyable wall
- AddWall(-1, x, y);
+ AddWall(-1, x, lines.length - 1 - y);
break;
case '#': // space reserved for players
- ReservePlayerSpace(x, y);
+ ReservePlayerSpace(x, lines.length - 1 - y);
break;
}
}
}
return true;
}
private World _world;
private EntityBuilder _entityBuilder;
private void ReservePlayerSpace(int tileX, int tileY)
{
// @TODO: Implement
}
private void AddWall(int hp, int tileX, int tileY)
{
_world.AddEntity(_entityBuilder.CreateWall(_lastGuid++, hp, tileX, tileY));
}
}
| false | true | public boolean TryLoad(int number, Ref<Integer> width, Ref<Integer> height)
{
FileHandle file = Gdx.files.internal("data/map" + number + ".txt");
if (!file.exists()) return false;
if (file.isDirectory()) return false;
String str = file.readString(Constants.DEFAULT_MAP_FILE_CHARSET);
String lines[] = str.split("\\r?\\n");
for (int y = 0; y < lines.length; ++y)
{
char[] chars = lines[y].toCharArray();
for (int x = 0; x < chars.length; ++x)
{
switch (chars[x])
{
case ' ': // empty space, can be destroyable wall
if (MathUtils.random() < Constants.WALL_CHANCE) AddWall(1, x, y);
break;
case 'X': // undestroyable wall
AddWall(-1, x, y);
break;
case '#': // space reserved for players
ReservePlayerSpace(x, y);
break;
}
}
}
return true;
}
| public boolean TryLoad(int number, Ref<Integer> width, Ref<Integer> height)
{
FileHandle file = Gdx.files.internal("data/map" + number + ".txt");
if (!file.exists()) return false;
if (file.isDirectory()) return false;
String str = file.readString(Constants.DEFAULT_MAP_FILE_CHARSET);
String lines[] = str.split("\\r?\\n");
for (int y = 0; y < lines.length; ++y)
{
char[] chars = lines[y].toCharArray();
for (int x = 0; x < chars.length; ++x)
{
switch (chars[x])
{
case ' ': // empty space, can be destroyable wall
if (MathUtils.random() < Constants.WALL_CHANCE) AddWall(1, x, lines.length - 1 - y);
break;
case 'X': // undestroyable wall
AddWall(-1, x, lines.length - 1 - y);
break;
case '#': // space reserved for players
ReservePlayerSpace(x, lines.length - 1 - y);
break;
}
}
}
return true;
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/editor/control/tools/structurepanel/AddElementTool.java b/E-Adventure/src/es/eucm/eadventure/editor/control/tools/structurepanel/AddElementTool.java
index cac54d6f..87efdf6a 100644
--- a/E-Adventure/src/es/eucm/eadventure/editor/control/tools/structurepanel/AddElementTool.java
+++ b/E-Adventure/src/es/eucm/eadventure/editor/control/tools/structurepanel/AddElementTool.java
@@ -1,132 +1,138 @@
/*******************************************************************************
* <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM>
* research group.
*
* Copyright 2005-2010 <e-UCM> research group.
*
* You can access a list of all the contributors to <e-Adventure> at:
* http://e-adventure.e-ucm.es/contributors
*
* <e-UCM> is a research group of the Department of Software Engineering
* and Artificial Intelligence at the Complutense University of Madrid
* (School of Computer Science).
*
* C Profesor Jose Garcia Santesmases sn,
* 28040 Madrid (Madrid), Spain.
*
* For more info please visit: <http://e-adventure.e-ucm.es> or
* <http://www.e-ucm.es>
*
* ****************************************************************************
*
* This file is part of <e-Adventure>, version 1.2.
*
* <e-Adventure> is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* <e-Adventure> is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with <e-Adventure>. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.eucm.eadventure.editor.control.tools.structurepanel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import es.eucm.eadventure.editor.control.Controller;
import es.eucm.eadventure.editor.control.tools.Tool;
import es.eucm.eadventure.editor.gui.structurepanel.StructureElement;
import es.eucm.eadventure.editor.gui.structurepanel.StructureListElement;
public class AddElementTool extends Tool {
private int type;
private StructureListElement element;
private JTable table;
private StructureElement newElement;
public AddElementTool( StructureListElement element, JTable table ) {
this.type = element.getDataControl( ).getAddableElements( )[0];
this.element = element;
this.table = table;
}
@Override
public boolean canUndo( ) {
return true;
}
@Override
public boolean doTool( ) {
if( element.getDataControl( ).canAddElement( type ) ) {
String defaultId = element.getDataControl( ).getDefaultId( type );
+ defaultId.replaceAll( " ", "_" );
+ if ( defaultId!=null && defaultId.length( )>0 && Character.isDigit( defaultId.charAt( 0 ) ) ){
+ defaultId="MH"+defaultId;
+ } else if (defaultId==null || defaultId.length( )==0){
+ defaultId="";
+ }
String id = defaultId;
int count = 0;
while( !Controller.getInstance( ).isElementIdValid( id, false ) ) {
count++;
id = defaultId + count;
}
if( element.getDataControl( ).addElement( type, id ) ) {
//( (StructureElement) table.getModel( ).getValueAt( element.getChildCount( ) - 1, 0 ) ).setJustCreated( true );
( (AbstractTableModel) table.getModel( ) ).fireTableDataChanged( );
/*SwingUtilities.invokeLater( new Runnable( ) {
public void run( ) {
if( table.editCellAt( element.getChildCount( ) - 1, 0 ) )
( (StructureElementCell) table.getEditorComponent( ) ).requestFocusInWindow( );
}
} );*/
table.changeSelection( element.getChildCount( ) - 1, 0, false, false );
newElement = element.getChild( element.getChildCount( ) - 1 );
return true;
}
}
return false;
}
@Override
public String getToolName( ) {
return "Add child";
}
@Override
public boolean undoTool( ) {
newElement.delete( false );
Controller.getInstance( ).updateStructure( );
return true;
}
@Override
public boolean canRedo( ) {
return false;
}
@Override
public boolean redoTool( ) {
return false;
}
@Override
public boolean combine( Tool other ) {
return false;
}
}
| true | true | public boolean doTool( ) {
if( element.getDataControl( ).canAddElement( type ) ) {
String defaultId = element.getDataControl( ).getDefaultId( type );
String id = defaultId;
int count = 0;
while( !Controller.getInstance( ).isElementIdValid( id, false ) ) {
count++;
id = defaultId + count;
}
if( element.getDataControl( ).addElement( type, id ) ) {
//( (StructureElement) table.getModel( ).getValueAt( element.getChildCount( ) - 1, 0 ) ).setJustCreated( true );
( (AbstractTableModel) table.getModel( ) ).fireTableDataChanged( );
/*SwingUtilities.invokeLater( new Runnable( ) {
public void run( ) {
if( table.editCellAt( element.getChildCount( ) - 1, 0 ) )
( (StructureElementCell) table.getEditorComponent( ) ).requestFocusInWindow( );
}
} );*/
table.changeSelection( element.getChildCount( ) - 1, 0, false, false );
newElement = element.getChild( element.getChildCount( ) - 1 );
return true;
}
}
| public boolean doTool( ) {
if( element.getDataControl( ).canAddElement( type ) ) {
String defaultId = element.getDataControl( ).getDefaultId( type );
defaultId.replaceAll( " ", "_" );
if ( defaultId!=null && defaultId.length( )>0 && Character.isDigit( defaultId.charAt( 0 ) ) ){
defaultId="MH"+defaultId;
} else if (defaultId==null || defaultId.length( )==0){
defaultId="";
}
String id = defaultId;
int count = 0;
while( !Controller.getInstance( ).isElementIdValid( id, false ) ) {
count++;
id = defaultId + count;
}
if( element.getDataControl( ).addElement( type, id ) ) {
//( (StructureElement) table.getModel( ).getValueAt( element.getChildCount( ) - 1, 0 ) ).setJustCreated( true );
( (AbstractTableModel) table.getModel( ) ).fireTableDataChanged( );
/*SwingUtilities.invokeLater( new Runnable( ) {
public void run( ) {
if( table.editCellAt( element.getChildCount( ) - 1, 0 ) )
( (StructureElementCell) table.getEditorComponent( ) ).requestFocusInWindow( );
}
} );*/
table.changeSelection( element.getChildCount( ) - 1, 0, false, false );
newElement = element.getChild( element.getChildCount( ) - 1 );
return true;
}
}
|
diff --git a/src/framework/utils/ApplicationInstaller.java b/src/framework/utils/ApplicationInstaller.java
index bb3f6493..734552f1 100644
--- a/src/framework/utils/ApplicationInstaller.java
+++ b/src/framework/utils/ApplicationInstaller.java
@@ -1,64 +1,64 @@
package framework.utils;
import junit.framework.Assert;
import test.cli.cloudify.CommandTestUtils;
public class ApplicationInstaller extends RecipeInstaller {
private static final int DEFAULT_INSTALL_APPLICATION_TIMEOUT = 30;
private String applicationName;
public ApplicationInstaller(String restUrl, String applicationName) {
super(restUrl, DEFAULT_INSTALL_APPLICATION_TIMEOUT);
this.applicationName = applicationName;
}
@Override
public String getInstallCommand() {
return "install-application";
}
@Override
public void assertInstall(String output) {
final String excpectedResult = "Application " + applicationName + " installed successfully";
if (!isExpectToFail()) {
AssertUtils.assertTrue(output.toLowerCase().contains(excpectedResult.toLowerCase()));
} else {
AssertUtils.assertTrue(output.toLowerCase().contains("operation failed"));
}
}
@Override
public String getUninstallCommand() {
return "uninstall-application";
}
@Override
public String getRecipeName() {
return applicationName;
}
@Override
public void assertUninstall(String output) {
final String excpectedResult = "Application " + applicationName + " uninstalled successfully";
AssertUtils.assertTrue(output.toLowerCase().contains(excpectedResult.toLowerCase()));
}
public void uninstallIfFound() {
if (getRestUrl() != null) {
- String command = "connect " + getRestUrl() + ";list-application";
+ String command = "connect " + getRestUrl() + ";list-applications";
String output;
try {
output = CommandTestUtils.runCommandAndWait(command);
if (output.contains(applicationName)) {
uninstall();
}
} catch (final Exception e) {
LogUtils.log(e.getMessage(), e);
Assert.fail(e.getMessage());
}
}
}
}
| true | true | public void uninstallIfFound() {
if (getRestUrl() != null) {
String command = "connect " + getRestUrl() + ";list-application";
String output;
try {
output = CommandTestUtils.runCommandAndWait(command);
if (output.contains(applicationName)) {
uninstall();
}
} catch (final Exception e) {
LogUtils.log(e.getMessage(), e);
Assert.fail(e.getMessage());
}
}
}
| public void uninstallIfFound() {
if (getRestUrl() != null) {
String command = "connect " + getRestUrl() + ";list-applications";
String output;
try {
output = CommandTestUtils.runCommandAndWait(command);
if (output.contains(applicationName)) {
uninstall();
}
} catch (final Exception e) {
LogUtils.log(e.getMessage(), e);
Assert.fail(e.getMessage());
}
}
}
|
diff --git a/src-vis/org/seasr/meandre/components/vis/temporal/SimileTimelineGenerator.java b/src-vis/org/seasr/meandre/components/vis/temporal/SimileTimelineGenerator.java
index 3643ee2f..927eeef4 100644
--- a/src-vis/org/seasr/meandre/components/vis/temporal/SimileTimelineGenerator.java
+++ b/src-vis/org/seasr/meandre/components/vis/temporal/SimileTimelineGenerator.java
@@ -1,375 +1,375 @@
/**
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, Board of Trustees-University of Illinois.
* All rights reserved.
*
* Developed by:
*
* Automated Learning Group
* National Center for Supercomputing Applications
* http://www.seasr.org
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal with the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of Automated Learning Group, The National Center for
* Supercomputing Applications, or University of Illinois, nor the names of
* its contributors may be used to endorse or promote products derived from
* this Software without specific prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* WITH THE SOFTWARE.
*/
package org.seasr.meandre.components.vis.temporal;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.VelocityContext;
import org.meandre.annotations.Component;
import org.meandre.annotations.ComponentInput;
import org.meandre.annotations.ComponentOutput;
import org.meandre.annotations.ComponentProperty;
import org.meandre.annotations.Component.Licenses;
import org.meandre.components.abstracts.AbstractExecutableComponent;
import org.meandre.core.ComponentContext;
import org.meandre.core.ComponentContextProperties;
import org.seasr.datatypes.BasicDataTypesTools;
import org.seasr.meandre.components.tools.Names;
import org.seasr.meandre.support.html.VelocityTemplateService;
import org.seasr.meandre.support.io.IOUtils;
import org.seasr.meandre.support.parsers.DataTypeParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import sun.misc.BASE64Encoder;
/**
* @author Lily Dong
* @author Boris Capitanu
*/
@Component(
creator = "Lily Dong",
description = "Generates the necessary HTML and XML files " +
"for viewing timeline and store them on the local machine. " +
"The two files will be stored under public/resources/timeline/file/. " +
"will be stored under public/resources/timeline/js/. " +
"For fast browse, dates are grouped into different time slices. " +
"The number of time slices is designed as a property. " +
"If granularity is not appropriate, adjusts this porperty.",
name = "Simile Timeline Generator",
tags = "simile, timeline",
rights = Licenses.UofINCSA,
baseURL="meandre://seasr.org/components/tools/",
dependency = {"protobuf-java-2.0.3.jar", "velocity-1.6.1-dep.jar"},
resources = {"SimileTimelineGenerator.vm"}
)
public class SimileTimelineGenerator extends AbstractExecutableComponent {
//------------------------------ INPUTS ------------------------------------------------------
@ComponentInput(
description = "The source XML document",
name = Names.PORT_XML
)
protected static final String IN_XML = Names.PORT_XML;
//------------------------------ OUTPUTS -----------------------------------------------------
@ComponentOutput(
description = "The HTML for the Simile Timeline viewer",
name = Names.PORT_HTML
)
protected static final String OUT_HTML = Names.PORT_HTML;
//------------------------------ PROPERTIES --------------------------------------------------
@ComponentProperty(
defaultValue = "10",
description = "The number of time slices desired",
name = Names.PROP_N_SLICES
)
protected static final String DATA_PROPERTY = Names.PROP_N_SLICES;
//--------------------------------------------------------------------------------------------
protected static final String simileVelocityTemplate =
"org/seasr/meandre/components/vis/temporal/SimileTimelineGenerator.vm";
/** Store document title */
private String docTitle;
/** Store the minimum value of year */
private int minYear;
/** Store the maximum value of year */
private int maxYear;
private VelocityContext _context;
//--------------------------------------------------------------------------------------------
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
_context = VelocityTemplateService.getInstance().getNewContext();
_context.put("ccp", ccp);
}
public void executeCallBack(ComponentContext cc) throws Exception {
Document doc = DataTypeParser.parseAsDomDocument(cc.getDataComponentFromInput(IN_XML));
String dirName = cc.getPublicResourcesDirectory() + File.separator;
dirName += "timeline" + File.separator;
File dir = new File(dirName);
if (!dir.exists())
if (!dir.mkdir())
throw new IOException("The directory '" + dirName + "' could not be created!");
console.finest("Set storage location to " + dirName);
String webUiUrl = cc.getWebUIUrl(true).toString();
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String htmlFileName = "myhtml" + formatter.format(now) + ".html",
xmlFileName = "myxml" + formatter.format(now) + ".xml";
String htmlLocation = webUiUrl + "public/resources/timeline/" + htmlFileName,
xmlLocation = webUiUrl + "public/resources/timeline/" + xmlFileName;
console.finest("htmlFileName=" + htmlFileName);
console.finest("xmlFileName=" + xmlFileName);
console.finest("htmlLocation=" + htmlLocation);
console.finest("xmlLocation=" + xmlLocation);
URI xmlURI = DataTypeParser.parseAsURI(dirName + xmlFileName);
URI htmlURI = DataTypeParser.parseAsURI(dirName + htmlFileName);
String simileXml = generateXML(doc);
Writer xmlWriter = IOUtils.getWriterForResource(xmlURI);
xmlWriter.write(simileXml);
xmlWriter.close();
String simileHtml = generateHTML(simileXml, xmlLocation);
Writer htmlWriter = IOUtils.getWriterForResource(htmlURI);
htmlWriter.write(simileHtml);
htmlWriter.close();
console.info("The Simile Timeline HTML content was created at " + htmlLocation);
console.info("The Simile Timeline XML content was created at " + xmlLocation);
cc.pushDataComponentToOutput(OUT_HTML, BasicDataTypesTools.stringToStrings(simileHtml));
}
public void disposeCallBack(ComponentContextProperties ccp) throws Exception {
}
//--------------------------------------------------------------------------------------------
private String generateHTML(String simileXml, String simileXmlUrl) throws Exception {
VelocityTemplateService velocity = VelocityTemplateService.getInstance();
_context.put("maxYear", maxYear);
_context.put("minYear", minYear);
_context.put("simileXmlBase64", new BASE64Encoder().encode(simileXml.getBytes()));
_context.put("simileXmlUrl", simileXmlUrl);
return velocity.generateOutput(_context, simileVelocityTemplate);
}
private String generateXML(Document doc) {
minYear = Integer.MAX_VALUE;
maxYear = Integer.MIN_VALUE;
//TODO: StringBuffer buf needs to be replaced with the XML document object
StringBuffer buf = new StringBuffer(); //Store XML
buf.append("<data>\n");
doc.getDocumentElement().normalize();
docTitle = doc.getDocumentElement().getAttribute("docID");
console.finest("Root element : " + docTitle);
NodeList dateNodes = doc.getElementsByTagName("date");
//getConsoleOut().println("Information of date");
for (int i = 0, iMax = dateNodes.getLength(); i < iMax; i++) {
Element elEntity = (Element)dateNodes.item(i);
String aDate = elEntity.getAttribute("value");
//standardize date
//getConsoleOut().println("time : " + aDate);
String month = null,
day = null,
year = null;
String startMonth = null,
endMonth = null;
- Pattern datePattern = Pattern.compile("(january|jan|feburary|feb|march|mar|" + //look for month
+ Pattern datePattern = Pattern.compile("(january|jan|february|feb|march|mar|" + //look for month
"april|apr|may|june|jun|july|jul|august|aug|september|sept|october|oct|"+
"november|nov|december|dec)");
Matcher dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for month
month = dateMatcher.group(1);
} else { //look for season
datePattern = Pattern.compile("(spring|summer|fall|winter)");
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
String season = dateMatcher.group(1);
if(season.equalsIgnoreCase("spring")) {
startMonth = "Mar 21";
endMonth = "June 20";
} else if(season.equalsIgnoreCase("summer")) {
startMonth = "June 21";
endMonth = "Sept 20";
} else if(season.equalsIgnoreCase("fall")) {
startMonth = "Sept 21";
endMonth = "Dec 20";
} else { //winter
startMonth = "Dec 21";
endMonth = "Mar 20";
}
}
}
datePattern = Pattern.compile("(\\b\\d{1}\\b)"); //look for day like 5
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
} else {
datePattern = Pattern.compile("(\\b\\d{2}\\b)"); //look for day like 21
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
}
}
//datePattern = Pattern.compile("(\\d{4})"); //look for year
datePattern = Pattern.compile("(\\d{3,4})"); //look for year with 3 or 4 digits
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for year
StringBuffer sbHtml = new StringBuffer();
int nr = 0;
NodeList sentenceNodes = elEntity.getElementsByTagName("sentence");
for (int idx = 0, idxMax = sentenceNodes.getLength(); idx < idxMax; idx++) {
Element elSentence = (Element)sentenceNodes.item(idx);
String docTitle = elSentence.getAttribute("docTitle");
String theSentence = elSentence.getTextContent();
int datePos = theSentence.toLowerCase().indexOf(aDate);
String str = "</font>";
int offset = datePos+aDate.length();
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
offset = datePos;
str = "<font color='red'>";
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
sbHtml.append("<div onclick='toggleVisibility(this)' style='position:relative' align='left'><b>Sentence ").append(++nr);
if (docTitle != null && docTitle.length() > 0)
sbHtml.append(" from '" + docTitle + "'");
sbHtml.append("</b><span style='display: ' align='left'><table><tr><td>").append(theSentence).append("</td></tr></table></span></div>");
}
String sentence = StringEscapeUtils.escapeXml(sbHtml.toString());
year = dateMatcher.group(1);
minYear = Math.min(minYear, Integer.parseInt(year));
maxYear = Math.max(maxYear, Integer.parseInt(year));
//year or month year or month day year
if(day == null)
if(month == null) { //season year
if(startMonth != null) {//spring or summer or fall or winter year
buf.append("<event start=\"").append(startMonth + " " + year).append("\" end=\"").append(endMonth + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //year
//if(Integer.parseInt(year) != 1832) {
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");//}
}
} else { //month year
String startDay = month + " 01";
int m = 1;
if(month.startsWith("feb"))
m = 2;
else if(month.startsWith("mar"))
m = 3;
else if(month.startsWith("apr"))
m = 4;
else if(month.startsWith("may"))
m = 5;
else if(month.startsWith("jun"))
m = 6;
else if(month.startsWith("jul"))
m = 7;
else if(month.startsWith("aug"))
m = 8;
else if(month.startsWith("sept"))
m = 9;
else if(month.startsWith("oct"))
m = 10;
else if(month.startsWith("nov"))
m = 11;
else if(month.startsWith("dec"))
m = 12;
int y = Integer.parseInt(year);
int numberOfDays = 31;
if (m == 4 || m == 6 || m == 9 || m == 11)
numberOfDays = 30;
else if (m == 2) {
boolean isLeapYear = (y % 4 == 0 && y % 100 != 0 || (y % 400 == 0));
if (isLeapYear)
numberOfDays = 29;
else
numberOfDays = 28;
}
String endDay = month + " " + Integer.toString(numberOfDays);
buf.append("<event start=\"").append(startDay + " " + year).append("\" end=\"").append(endDay + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
else {
if(month == null) {//year
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //month day year
buf.append("<event start=\"").append(month + " " + day + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
}
}
}
buf.append("</data>");
return buf.toString();
}
}
| true | true | private String generateXML(Document doc) {
minYear = Integer.MAX_VALUE;
maxYear = Integer.MIN_VALUE;
//TODO: StringBuffer buf needs to be replaced with the XML document object
StringBuffer buf = new StringBuffer(); //Store XML
buf.append("<data>\n");
doc.getDocumentElement().normalize();
docTitle = doc.getDocumentElement().getAttribute("docID");
console.finest("Root element : " + docTitle);
NodeList dateNodes = doc.getElementsByTagName("date");
//getConsoleOut().println("Information of date");
for (int i = 0, iMax = dateNodes.getLength(); i < iMax; i++) {
Element elEntity = (Element)dateNodes.item(i);
String aDate = elEntity.getAttribute("value");
//standardize date
//getConsoleOut().println("time : " + aDate);
String month = null,
day = null,
year = null;
String startMonth = null,
endMonth = null;
Pattern datePattern = Pattern.compile("(january|jan|feburary|feb|march|mar|" + //look for month
"april|apr|may|june|jun|july|jul|august|aug|september|sept|october|oct|"+
"november|nov|december|dec)");
Matcher dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for month
month = dateMatcher.group(1);
} else { //look for season
datePattern = Pattern.compile("(spring|summer|fall|winter)");
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
String season = dateMatcher.group(1);
if(season.equalsIgnoreCase("spring")) {
startMonth = "Mar 21";
endMonth = "June 20";
} else if(season.equalsIgnoreCase("summer")) {
startMonth = "June 21";
endMonth = "Sept 20";
} else if(season.equalsIgnoreCase("fall")) {
startMonth = "Sept 21";
endMonth = "Dec 20";
} else { //winter
startMonth = "Dec 21";
endMonth = "Mar 20";
}
}
}
datePattern = Pattern.compile("(\\b\\d{1}\\b)"); //look for day like 5
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
} else {
datePattern = Pattern.compile("(\\b\\d{2}\\b)"); //look for day like 21
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
}
}
//datePattern = Pattern.compile("(\\d{4})"); //look for year
datePattern = Pattern.compile("(\\d{3,4})"); //look for year with 3 or 4 digits
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for year
StringBuffer sbHtml = new StringBuffer();
int nr = 0;
NodeList sentenceNodes = elEntity.getElementsByTagName("sentence");
for (int idx = 0, idxMax = sentenceNodes.getLength(); idx < idxMax; idx++) {
Element elSentence = (Element)sentenceNodes.item(idx);
String docTitle = elSentence.getAttribute("docTitle");
String theSentence = elSentence.getTextContent();
int datePos = theSentence.toLowerCase().indexOf(aDate);
String str = "</font>";
int offset = datePos+aDate.length();
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
offset = datePos;
str = "<font color='red'>";
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
sbHtml.append("<div onclick='toggleVisibility(this)' style='position:relative' align='left'><b>Sentence ").append(++nr);
if (docTitle != null && docTitle.length() > 0)
sbHtml.append(" from '" + docTitle + "'");
sbHtml.append("</b><span style='display: ' align='left'><table><tr><td>").append(theSentence).append("</td></tr></table></span></div>");
}
String sentence = StringEscapeUtils.escapeXml(sbHtml.toString());
year = dateMatcher.group(1);
minYear = Math.min(minYear, Integer.parseInt(year));
maxYear = Math.max(maxYear, Integer.parseInt(year));
//year or month year or month day year
if(day == null)
if(month == null) { //season year
if(startMonth != null) {//spring or summer or fall or winter year
buf.append("<event start=\"").append(startMonth + " " + year).append("\" end=\"").append(endMonth + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //year
//if(Integer.parseInt(year) != 1832) {
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");//}
}
} else { //month year
String startDay = month + " 01";
int m = 1;
if(month.startsWith("feb"))
m = 2;
else if(month.startsWith("mar"))
m = 3;
else if(month.startsWith("apr"))
m = 4;
else if(month.startsWith("may"))
m = 5;
else if(month.startsWith("jun"))
m = 6;
else if(month.startsWith("jul"))
m = 7;
else if(month.startsWith("aug"))
m = 8;
else if(month.startsWith("sept"))
m = 9;
else if(month.startsWith("oct"))
m = 10;
else if(month.startsWith("nov"))
m = 11;
else if(month.startsWith("dec"))
m = 12;
int y = Integer.parseInt(year);
int numberOfDays = 31;
if (m == 4 || m == 6 || m == 9 || m == 11)
numberOfDays = 30;
else if (m == 2) {
boolean isLeapYear = (y % 4 == 0 && y % 100 != 0 || (y % 400 == 0));
if (isLeapYear)
numberOfDays = 29;
else
numberOfDays = 28;
}
String endDay = month + " " + Integer.toString(numberOfDays);
buf.append("<event start=\"").append(startDay + " " + year).append("\" end=\"").append(endDay + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
else {
if(month == null) {//year
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //month day year
buf.append("<event start=\"").append(month + " " + day + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
}
}
}
| private String generateXML(Document doc) {
minYear = Integer.MAX_VALUE;
maxYear = Integer.MIN_VALUE;
//TODO: StringBuffer buf needs to be replaced with the XML document object
StringBuffer buf = new StringBuffer(); //Store XML
buf.append("<data>\n");
doc.getDocumentElement().normalize();
docTitle = doc.getDocumentElement().getAttribute("docID");
console.finest("Root element : " + docTitle);
NodeList dateNodes = doc.getElementsByTagName("date");
//getConsoleOut().println("Information of date");
for (int i = 0, iMax = dateNodes.getLength(); i < iMax; i++) {
Element elEntity = (Element)dateNodes.item(i);
String aDate = elEntity.getAttribute("value");
//standardize date
//getConsoleOut().println("time : " + aDate);
String month = null,
day = null,
year = null;
String startMonth = null,
endMonth = null;
Pattern datePattern = Pattern.compile("(january|jan|february|feb|march|mar|" + //look for month
"april|apr|may|june|jun|july|jul|august|aug|september|sept|october|oct|"+
"november|nov|december|dec)");
Matcher dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for month
month = dateMatcher.group(1);
} else { //look for season
datePattern = Pattern.compile("(spring|summer|fall|winter)");
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
String season = dateMatcher.group(1);
if(season.equalsIgnoreCase("spring")) {
startMonth = "Mar 21";
endMonth = "June 20";
} else if(season.equalsIgnoreCase("summer")) {
startMonth = "June 21";
endMonth = "Sept 20";
} else if(season.equalsIgnoreCase("fall")) {
startMonth = "Sept 21";
endMonth = "Dec 20";
} else { //winter
startMonth = "Dec 21";
endMonth = "Mar 20";
}
}
}
datePattern = Pattern.compile("(\\b\\d{1}\\b)"); //look for day like 5
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
} else {
datePattern = Pattern.compile("(\\b\\d{2}\\b)"); //look for day like 21
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) {
day = dateMatcher.group(1);
}
}
//datePattern = Pattern.compile("(\\d{4})"); //look for year
datePattern = Pattern.compile("(\\d{3,4})"); //look for year with 3 or 4 digits
dateMatcher = datePattern.matcher(aDate);
if(dateMatcher.find()) { //look for year
StringBuffer sbHtml = new StringBuffer();
int nr = 0;
NodeList sentenceNodes = elEntity.getElementsByTagName("sentence");
for (int idx = 0, idxMax = sentenceNodes.getLength(); idx < idxMax; idx++) {
Element elSentence = (Element)sentenceNodes.item(idx);
String docTitle = elSentence.getAttribute("docTitle");
String theSentence = elSentence.getTextContent();
int datePos = theSentence.toLowerCase().indexOf(aDate);
String str = "</font>";
int offset = datePos+aDate.length();
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
offset = datePos;
str = "<font color='red'>";
theSentence = new StringBuffer(theSentence).insert(offset, str).toString();
sbHtml.append("<div onclick='toggleVisibility(this)' style='position:relative' align='left'><b>Sentence ").append(++nr);
if (docTitle != null && docTitle.length() > 0)
sbHtml.append(" from '" + docTitle + "'");
sbHtml.append("</b><span style='display: ' align='left'><table><tr><td>").append(theSentence).append("</td></tr></table></span></div>");
}
String sentence = StringEscapeUtils.escapeXml(sbHtml.toString());
year = dateMatcher.group(1);
minYear = Math.min(minYear, Integer.parseInt(year));
maxYear = Math.max(maxYear, Integer.parseInt(year));
//year or month year or month day year
if(day == null)
if(month == null) { //season year
if(startMonth != null) {//spring or summer or fall or winter year
buf.append("<event start=\"").append(startMonth + " " + year).append("\" end=\"").append(endMonth + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //year
//if(Integer.parseInt(year) != 1832) {
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");//}
}
} else { //month year
String startDay = month + " 01";
int m = 1;
if(month.startsWith("feb"))
m = 2;
else if(month.startsWith("mar"))
m = 3;
else if(month.startsWith("apr"))
m = 4;
else if(month.startsWith("may"))
m = 5;
else if(month.startsWith("jun"))
m = 6;
else if(month.startsWith("jul"))
m = 7;
else if(month.startsWith("aug"))
m = 8;
else if(month.startsWith("sept"))
m = 9;
else if(month.startsWith("oct"))
m = 10;
else if(month.startsWith("nov"))
m = 11;
else if(month.startsWith("dec"))
m = 12;
int y = Integer.parseInt(year);
int numberOfDays = 31;
if (m == 4 || m == 6 || m == 9 || m == 11)
numberOfDays = 30;
else if (m == 2) {
boolean isLeapYear = (y % 4 == 0 && y % 100 != 0 || (y % 400 == 0));
if (isLeapYear)
numberOfDays = 29;
else
numberOfDays = 28;
}
String endDay = month + " " + Integer.toString(numberOfDays);
buf.append("<event start=\"").append(startDay + " " + year).append("\" end=\"").append(endDay + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
else {
if(month == null) {//year
buf.append("<event start=\"").append(year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
} else { //month day year
buf.append("<event start=\"").append(month + " " + day + " " + year).append("\" title=\"").append(aDate+"("+nr+")").append("\">\n").append(sentence).append("\n");
buf.append("</event>\n");
}
}
}
}
|
diff --git a/modules/extra/jetty-jboss/src/main/java/org/jboss/jetty/JBossWebXmlConfiguration.java b/modules/extra/jetty-jboss/src/main/java/org/jboss/jetty/JBossWebXmlConfiguration.java
index 1ad7a6bb9..cdfb40430 100644
--- a/modules/extra/jetty-jboss/src/main/java/org/jboss/jetty/JBossWebXmlConfiguration.java
+++ b/modules/extra/jetty-jboss/src/main/java/org/jboss/jetty/JBossWebXmlConfiguration.java
@@ -1,108 +1,108 @@
//========================================================================
//$Id$
//Copyright 2006 Mort Bay Consulting Pty. 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 org.jboss.jetty;
import org.jboss.jetty.security.JBossUserRealm;
import org.jboss.logging.Logger;
import org.jboss.metadata.WebMetaData;
import org.mortbay.jetty.security.UserRealm;
import org.mortbay.jetty.webapp.WebXmlConfiguration;
import org.mortbay.xml.XmlParser;
/**
* JBossWebXmlConfiguration
*
* Extends the jetty WebXmlConfiguration to provide jboss
* handling of various elements in the web.xml
*/
public class JBossWebXmlConfiguration extends WebXmlConfiguration
{
protected static Logger __log=Logger.getLogger(JBossWebAppContext.class);
public JBossWebXmlConfiguration() throws ClassNotFoundException
{
super();
}
public JBossWebAppContext getJBossWebApplicationContext()
{
return (JBossWebAppContext)getWebAppContext();
}
protected void initWebXmlElement(String element,org.mortbay.xml.XmlParser.Node node) throws Exception
{
//avoid jetty printing a debug message about not implementing these elements
//because jboss implements it for us
if("resource-ref".equals(element)||"resource-env-ref".equals(element)||"env-entry".equals(element)
||"ejb-ref".equals(element)||"ejb-local-ref".equals(element)||"security-domain".equals(element))
{
//ignore
}
// these are handled by Jetty
else
super.initWebXmlElement(element,node);
}
protected void initSessionConfig(XmlParser.Node node)
{
XmlParser.Node tNode=node.get("session-timeout");
if(tNode!=null)
{
getJBossWebApplicationContext()._timeOutPresent=true;
getJBossWebApplicationContext()._timeOutMinutes=Integer.parseInt(tNode.toString(false,true));
}
// pass up to our super class so they can do all this again !
super.initSessionConfig(node);
}
- protected void initLoginConfig(XmlParser.Node node)
+ protected void initLoginConfig(XmlParser.Node node) throws Exception
{
// check if a realm has been explicitly set
String realmName=null;
UserRealm userRealm = getJBossWebApplicationContext().getSecurityHandler().getUserRealm();
if (userRealm!= null)
realmName=userRealm.getName();
//use a security domain from jboss-web.xml
if (null==realmName)
{
WebMetaData metaData = getJBossWebApplicationContext()._webApp.getMetaData();
realmName = metaData.getSecurityDomain();
if (null!=realmName)
{
if (realmName.endsWith("/"))
realmName = realmName.substring (0, realmName.length());
int idx = realmName.lastIndexOf('/');
if (idx >= 0)
realmName = realmName.substring(idx+1);
}
}
if(__log.isDebugEnabled())
__log.debug("Realm is : "+realmName);
if (realmName != null)
{
JBossUserRealm realm = new JBossUserRealm(realmName,getJBossWebApplicationContext().getSubjectAttribute());
getJBossWebApplicationContext().setRealm(realm);
getJBossWebApplicationContext().getSecurityHandler().setUserRealm(realm);
}
super.initLoginConfig(node);
}
}
| true | true | protected void initLoginConfig(XmlParser.Node node)
{
// check if a realm has been explicitly set
String realmName=null;
UserRealm userRealm = getJBossWebApplicationContext().getSecurityHandler().getUserRealm();
if (userRealm!= null)
realmName=userRealm.getName();
//use a security domain from jboss-web.xml
if (null==realmName)
{
WebMetaData metaData = getJBossWebApplicationContext()._webApp.getMetaData();
realmName = metaData.getSecurityDomain();
if (null!=realmName)
{
if (realmName.endsWith("/"))
realmName = realmName.substring (0, realmName.length());
int idx = realmName.lastIndexOf('/');
if (idx >= 0)
realmName = realmName.substring(idx+1);
}
}
if(__log.isDebugEnabled())
__log.debug("Realm is : "+realmName);
if (realmName != null)
{
JBossUserRealm realm = new JBossUserRealm(realmName,getJBossWebApplicationContext().getSubjectAttribute());
getJBossWebApplicationContext().setRealm(realm);
getJBossWebApplicationContext().getSecurityHandler().setUserRealm(realm);
}
super.initLoginConfig(node);
}
| protected void initLoginConfig(XmlParser.Node node) throws Exception
{
// check if a realm has been explicitly set
String realmName=null;
UserRealm userRealm = getJBossWebApplicationContext().getSecurityHandler().getUserRealm();
if (userRealm!= null)
realmName=userRealm.getName();
//use a security domain from jboss-web.xml
if (null==realmName)
{
WebMetaData metaData = getJBossWebApplicationContext()._webApp.getMetaData();
realmName = metaData.getSecurityDomain();
if (null!=realmName)
{
if (realmName.endsWith("/"))
realmName = realmName.substring (0, realmName.length());
int idx = realmName.lastIndexOf('/');
if (idx >= 0)
realmName = realmName.substring(idx+1);
}
}
if(__log.isDebugEnabled())
__log.debug("Realm is : "+realmName);
if (realmName != null)
{
JBossUserRealm realm = new JBossUserRealm(realmName,getJBossWebApplicationContext().getSubjectAttribute());
getJBossWebApplicationContext().setRealm(realm);
getJBossWebApplicationContext().getSecurityHandler().setUserRealm(realm);
}
super.initLoginConfig(node);
}
|
diff --git a/src/com/android/packageinstaller/PackageInstallerActivity.java b/src/com/android/packageinstaller/PackageInstallerActivity.java
index d3b2a947..8771a3ec 100644
--- a/src/com/android/packageinstaller/PackageInstallerActivity.java
+++ b/src/com/android/packageinstaller/PackageInstallerActivity.java
@@ -1,608 +1,609 @@
/*
**
** Copyright 2007, 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.packageinstaller;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageUserState;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageParser;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AppSecurityPermissions;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
/*
* This activity is launched when a new application is installed via side loading
* The package is first parsed and the user is notified of parse errors via a dialog.
* If the package is successfully parsed, the user is notified to turn on the install unknown
* applications setting. A memory check is made at this point and the user is notified of out
* of memory conditions if any. If the package is already existing on the device,
* a confirmation dialog (to replace the existing package) is presented to the user.
* Based on the user response the package is then installed by launching InstallAppConfirm
* sub activity. All state transitions are handled in this activity
*/
public class PackageInstallerActivity extends Activity implements OnCancelListener, OnClickListener {
private static final String TAG = "PackageInstaller";
private Uri mPackageURI;
private Uri mOriginatingURI;
private Uri mReferrerURI;
private boolean localLOGV = false;
PackageManager mPm;
PackageInfo mPkgInfo;
ApplicationInfo mSourceInfo;
// ApplicationInfo object primarily used for already existing applications
private ApplicationInfo mAppInfo = null;
// View for install progress
View mInstallConfirm;
// Buttons to indicate user acceptance
private Button mOk;
private Button mCancel;
CaffeinatedScrollView mScrollView = null;
private boolean mOkCanInstall = false;
static final String PREFS_ALLOWED_SOURCES = "allowed_sources";
// Dialog identifiers used in showDialog
private static final int DLG_BASE = 0;
private static final int DLG_UNKNOWN_APPS = DLG_BASE + 1;
private static final int DLG_PACKAGE_ERROR = DLG_BASE + 2;
private static final int DLG_OUT_OF_SPACE = DLG_BASE + 3;
private static final int DLG_INSTALL_ERROR = DLG_BASE + 4;
private static final int DLG_ALLOW_SOURCE = DLG_BASE + 5;
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public static class TabsAdapter extends PagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private final Rect mTempRect = new Rect();
static final class TabInfo {
private final String tag;
private final View view;
TabInfo(String _tag, View _view) {
tag = _tag;
view = _view;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public TabsAdapter(Activity activity, TabHost tabHost, ViewPager pager) {
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(TabHost.TabSpec tabSpec, View view) {
tabSpec.setContent(new DummyTabFactory(mContext));
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, view);
mTabs.add(info);
mTabHost.addTab(tabSpec);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = mTabs.get(position).view;
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
// Scroll the current tab into visibility if needed.
View tab = widget.getChildTabViewAt(position);
mTempRect.set(tab.getLeft(), tab.getTop(), tab.getRight(), tab.getBottom());
widget.requestRectangleOnScreen(mTempRect, false);
// Make sure the scrollbars are visible for a moment after selection
final View contentView = mTabs.get(position).view;
if (contentView instanceof CaffeinatedScrollView) {
((CaffeinatedScrollView) contentView).awakenScrollBars();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
private void startInstallConfirm() {
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager);
boolean permVisible = false;
mScrollView = null;
mOkCanInstall = false;
int msg = 0;
if (mPkgInfo != null) {
AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo);
final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL);
final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE);
if (mAppInfo != null) {
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system
: R.string.install_confirm_question_update;
mScrollView = new CaffeinatedScrollView(this);
mScrollView.setFillViewport(true);
if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) {
permVisible = true;
mScrollView.addView(perms.getPermissionsView(
AppSecurityPermissions.WHICH_NEW));
} else {
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView label = (TextView)inflater.inflate(R.layout.label, null);
label.setText(R.string.no_new_perms);
mScrollView.addView(label);
}
adapter.addTab(tabHost.newTabSpec("new").setIndicator(
getText(R.string.newPerms)), mScrollView);
} else {
findViewById(R.id.tabscontainer).setVisibility(View.GONE);
+ findViewById(R.id.divider).setVisibility(View.VISIBLE);
}
if (NP > 0 || ND > 0) {
permVisible = true;
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View root = inflater.inflate(R.layout.permissions_list, null);
if (mScrollView == null) {
mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview);
}
if (NP > 0) {
((ViewGroup)root.findViewById(R.id.privacylist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL));
} else {
root.findViewById(R.id.privacylist).setVisibility(View.GONE);
}
if (ND > 0) {
((ViewGroup)root.findViewById(R.id.devicelist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE));
} else {
root.findViewById(R.id.devicelist).setVisibility(View.GONE);
}
adapter.addTab(tabHost.newTabSpec("all").setIndicator(
getText(R.string.allPerms)), root);
}
}
if (!permVisible) {
if (msg == 0) {
if (mAppInfo != null) {
// This is an update to an application, but there are no
// permissions at all.
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system_no_perms
: R.string.install_confirm_question_update_no_perms;
} else {
// This is a new application with no permissions.
msg = R.string.install_confirm_question_no_perms;
}
}
- tabHost.setVisibility(View.INVISIBLE);
+ tabHost.setVisibility(View.GONE);
}
if (msg != 0) {
((TextView)findViewById(R.id.install_confirm_question)).setText(msg);
}
mInstallConfirm.setVisibility(View.VISIBLE);
mOk = (Button)findViewById(R.id.ok_button);
mCancel = (Button)findViewById(R.id.cancel_button);
mOk.setOnClickListener(this);
mCancel.setOnClickListener(this);
if (mScrollView == null) {
// There is nothing to scroll view, so the ok button is immediately
// set to install.
mOk.setText(R.string.install);
mOkCanInstall = true;
} else {
mScrollView.setFullScrollAction(new Runnable() {
@Override
public void run() {
mOk.setText(R.string.install);
mOkCanInstall = true;
}
});
}
}
private void showDialogInner(int id) {
// TODO better fix for this? Remove dialog so that it gets created again
removeDialog(id);
showDialog(id);
}
@Override
public Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case DLG_UNKNOWN_APPS:
return new AlertDialog.Builder(this)
.setTitle(R.string.unknown_apps_dlg_title)
.setMessage(R.string.unknown_apps_dlg_text)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "Finishing off activity so that user can navigate to settings manually");
finish();
}})
.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "Launching settings");
launchSettingsAppAndFinish();
}
})
.setOnCancelListener(this)
.create();
case DLG_PACKAGE_ERROR :
return new AlertDialog.Builder(this)
.setTitle(R.string.Parse_error_dlg_title)
.setMessage(R.string.Parse_error_dlg_text)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setOnCancelListener(this)
.create();
case DLG_OUT_OF_SPACE:
// Guaranteed not to be null. will default to package name if not set by app
CharSequence appTitle = mPm.getApplicationLabel(mPkgInfo.applicationInfo);
String dlgText = getString(R.string.out_of_space_dlg_text,
appTitle.toString());
return new AlertDialog.Builder(this)
.setTitle(R.string.out_of_space_dlg_title)
.setMessage(dlgText)
.setPositiveButton(R.string.manage_applications, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//launch manage applications
Intent intent = new Intent("android.intent.action.MANAGE_PACKAGE_STORAGE");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "Canceling installation");
finish();
}
})
.setOnCancelListener(this)
.create();
case DLG_INSTALL_ERROR :
// Guaranteed not to be null. will default to package name if not set by app
CharSequence appTitle1 = mPm.getApplicationLabel(mPkgInfo.applicationInfo);
String dlgText1 = getString(R.string.install_failed_msg,
appTitle1.toString());
return new AlertDialog.Builder(this)
.setTitle(R.string.install_failed)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setMessage(dlgText1)
.setOnCancelListener(this)
.create();
case DLG_ALLOW_SOURCE:
CharSequence appTitle2 = mPm.getApplicationLabel(mSourceInfo);
String dlgText2 = getString(R.string.allow_source_dlg_text,
appTitle2.toString());
return new AlertDialog.Builder(this)
.setTitle(R.string.allow_source_dlg_title)
.setMessage(dlgText2)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setResult(RESULT_CANCELED);
finish();
}})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES,
Context.MODE_PRIVATE);
prefs.edit().putBoolean(mSourceInfo.packageName, true).apply();
startInstallConfirm();
}
})
.setOnCancelListener(this)
.create();
}
return null;
}
private void launchSettingsAppAndFinish() {
// Create an intent to launch SettingsTwo activity
Intent launchSettingsIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
launchSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchSettingsIntent);
finish();
}
private boolean isInstallingUnknownAppsAllowed() {
return Settings.Global.getInt(getContentResolver(),
Settings.Global.INSTALL_NON_MARKET_APPS, 0) > 0;
}
private void initiateInstall() {
String pkgName = mPkgInfo.packageName;
// Check if there is already a package on the device with this name
// but it has been renamed to something else.
String[] oldName = mPm.canonicalToCurrentPackageNames(new String[] { pkgName });
if (oldName != null && oldName.length > 0 && oldName[0] != null) {
pkgName = oldName[0];
mPkgInfo.packageName = pkgName;
mPkgInfo.applicationInfo.packageName = pkgName;
}
// Check if package is already installed. display confirmation dialog if replacing pkg
try {
// This is a little convoluted because we want to get all uninstalled
// apps, but this may include apps with just data, and if it is just
// data we still want to count it as "installed".
mAppInfo = mPm.getApplicationInfo(pkgName,
PackageManager.GET_UNINSTALLED_PACKAGES);
if ((mAppInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
mAppInfo = null;
}
} catch (NameNotFoundException e) {
mAppInfo = null;
}
startInstallConfirm();
}
void setPmResult(int pmResult) {
Intent result = new Intent();
result.putExtra(Intent.EXTRA_INSTALL_RESULT, pmResult);
setResult(pmResult == PackageManager.INSTALL_SUCCEEDED
? RESULT_OK : RESULT_FIRST_USER, result);
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// get intent information
final Intent intent = getIntent();
mPackageURI = intent.getData();
mOriginatingURI = intent.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI);
mReferrerURI = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
mPm = getPackageManager();
final String scheme = mPackageURI.getScheme();
if (scheme != null && !"file".equals(scheme) && !"package".equals(scheme)) {
Log.w(TAG, "Unsupported scheme " + scheme);
setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI);
return;
}
final PackageUtil.AppSnippet as;
if ("package".equals(mPackageURI.getScheme())) {
try {
mPkgInfo = mPm.getPackageInfo(mPackageURI.getSchemeSpecificPart(),
PackageManager.GET_PERMISSIONS | PackageManager.GET_UNINSTALLED_PACKAGES);
} catch (NameNotFoundException e) {
}
if (mPkgInfo == null) {
Log.w(TAG, "Requested package " + mPackageURI.getScheme()
+ " not available. Discontinuing installation");
showDialogInner(DLG_PACKAGE_ERROR);
setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
return;
}
as = new PackageUtil.AppSnippet(mPm.getApplicationLabel(mPkgInfo.applicationInfo),
mPm.getApplicationIcon(mPkgInfo.applicationInfo));
} else {
final File sourceFile = new File(mPackageURI.getPath());
PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile);
// Check for parse errors
if (parsed == null) {
Log.w(TAG, "Parse error when parsing manifest. Discontinuing installation");
showDialogInner(DLG_PACKAGE_ERROR);
setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
return;
}
mPkgInfo = PackageParser.generatePackageInfo(parsed, null,
PackageManager.GET_PERMISSIONS, 0, 0, null,
new PackageUserState());
as = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile);
}
//set view
setContentView(R.layout.install_start);
mInstallConfirm = findViewById(R.id.install_confirm_panel);
mInstallConfirm.setVisibility(View.INVISIBLE);
PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet);
// Deal with install source.
String callerPackage = getCallingPackage();
if (callerPackage != null && intent.getBooleanExtra(
Intent.EXTRA_NOT_UNKNOWN_SOURCE, false)) {
try {
mSourceInfo = mPm.getApplicationInfo(callerPackage, 0);
if (mSourceInfo != null) {
if ((mSourceInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
// System apps don't need to be approved.
initiateInstall();
return;
}
/* for now this is disabled, since the user would need to
* have enabled the global "unknown sources" setting in the
* first place in order to get here.
SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES,
Context.MODE_PRIVATE);
if (prefs.getBoolean(mSourceInfo.packageName, false)) {
// User has already allowed this one.
initiateInstall();
return;
}
//ask user to enable setting first
showDialogInner(DLG_ALLOW_SOURCE);
return;
*/
}
} catch (NameNotFoundException e) {
}
}
// Check unknown sources.
if (!isInstallingUnknownAppsAllowed()) {
//ask user to enable setting first
showDialogInner(DLG_UNKNOWN_APPS);
return;
}
initiateInstall();
}
// Generic handling when pressing back key
public void onCancel(DialogInterface dialog) {
finish();
}
public void onClick(View v) {
if(v == mOk) {
if (mOkCanInstall || mScrollView == null) {
// Start subactivity to actually install the application
Intent newIntent = new Intent();
newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO,
mPkgInfo.applicationInfo);
newIntent.setData(mPackageURI);
newIntent.setClass(this, InstallAppProgress.class);
String installerPackageName = getIntent().getStringExtra(
Intent.EXTRA_INSTALLER_PACKAGE_NAME);
if (mOriginatingURI != null) {
newIntent.putExtra(Intent.EXTRA_ORIGINATING_URI, mOriginatingURI);
}
if (mReferrerURI != null) {
newIntent.putExtra(Intent.EXTRA_REFERRER, mReferrerURI);
}
if (installerPackageName != null) {
newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
installerPackageName);
}
if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
newIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
newIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
}
if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI);
startActivity(newIntent);
finish();
} else {
mScrollView.pageScroll(View.FOCUS_DOWN);
}
} else if(v == mCancel) {
// Cancel and finish
setResult(RESULT_CANCELED);
finish();
}
}
}
| false | true | private void startInstallConfirm() {
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager);
boolean permVisible = false;
mScrollView = null;
mOkCanInstall = false;
int msg = 0;
if (mPkgInfo != null) {
AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo);
final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL);
final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE);
if (mAppInfo != null) {
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system
: R.string.install_confirm_question_update;
mScrollView = new CaffeinatedScrollView(this);
mScrollView.setFillViewport(true);
if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) {
permVisible = true;
mScrollView.addView(perms.getPermissionsView(
AppSecurityPermissions.WHICH_NEW));
} else {
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView label = (TextView)inflater.inflate(R.layout.label, null);
label.setText(R.string.no_new_perms);
mScrollView.addView(label);
}
adapter.addTab(tabHost.newTabSpec("new").setIndicator(
getText(R.string.newPerms)), mScrollView);
} else {
findViewById(R.id.tabscontainer).setVisibility(View.GONE);
}
if (NP > 0 || ND > 0) {
permVisible = true;
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View root = inflater.inflate(R.layout.permissions_list, null);
if (mScrollView == null) {
mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview);
}
if (NP > 0) {
((ViewGroup)root.findViewById(R.id.privacylist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL));
} else {
root.findViewById(R.id.privacylist).setVisibility(View.GONE);
}
if (ND > 0) {
((ViewGroup)root.findViewById(R.id.devicelist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE));
} else {
root.findViewById(R.id.devicelist).setVisibility(View.GONE);
}
adapter.addTab(tabHost.newTabSpec("all").setIndicator(
getText(R.string.allPerms)), root);
}
}
if (!permVisible) {
if (msg == 0) {
if (mAppInfo != null) {
// This is an update to an application, but there are no
// permissions at all.
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system_no_perms
: R.string.install_confirm_question_update_no_perms;
} else {
// This is a new application with no permissions.
msg = R.string.install_confirm_question_no_perms;
}
}
tabHost.setVisibility(View.INVISIBLE);
}
if (msg != 0) {
((TextView)findViewById(R.id.install_confirm_question)).setText(msg);
}
mInstallConfirm.setVisibility(View.VISIBLE);
mOk = (Button)findViewById(R.id.ok_button);
mCancel = (Button)findViewById(R.id.cancel_button);
mOk.setOnClickListener(this);
mCancel.setOnClickListener(this);
if (mScrollView == null) {
// There is nothing to scroll view, so the ok button is immediately
// set to install.
mOk.setText(R.string.install);
mOkCanInstall = true;
} else {
mScrollView.setFullScrollAction(new Runnable() {
@Override
public void run() {
mOk.setText(R.string.install);
mOkCanInstall = true;
}
});
}
}
| private void startInstallConfirm() {
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager);
boolean permVisible = false;
mScrollView = null;
mOkCanInstall = false;
int msg = 0;
if (mPkgInfo != null) {
AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo);
final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL);
final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE);
if (mAppInfo != null) {
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system
: R.string.install_confirm_question_update;
mScrollView = new CaffeinatedScrollView(this);
mScrollView.setFillViewport(true);
if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) {
permVisible = true;
mScrollView.addView(perms.getPermissionsView(
AppSecurityPermissions.WHICH_NEW));
} else {
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView label = (TextView)inflater.inflate(R.layout.label, null);
label.setText(R.string.no_new_perms);
mScrollView.addView(label);
}
adapter.addTab(tabHost.newTabSpec("new").setIndicator(
getText(R.string.newPerms)), mScrollView);
} else {
findViewById(R.id.tabscontainer).setVisibility(View.GONE);
findViewById(R.id.divider).setVisibility(View.VISIBLE);
}
if (NP > 0 || ND > 0) {
permVisible = true;
LayoutInflater inflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View root = inflater.inflate(R.layout.permissions_list, null);
if (mScrollView == null) {
mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview);
}
if (NP > 0) {
((ViewGroup)root.findViewById(R.id.privacylist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL));
} else {
root.findViewById(R.id.privacylist).setVisibility(View.GONE);
}
if (ND > 0) {
((ViewGroup)root.findViewById(R.id.devicelist)).addView(
perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE));
} else {
root.findViewById(R.id.devicelist).setVisibility(View.GONE);
}
adapter.addTab(tabHost.newTabSpec("all").setIndicator(
getText(R.string.allPerms)), root);
}
}
if (!permVisible) {
if (msg == 0) {
if (mAppInfo != null) {
// This is an update to an application, but there are no
// permissions at all.
msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
? R.string.install_confirm_question_update_system_no_perms
: R.string.install_confirm_question_update_no_perms;
} else {
// This is a new application with no permissions.
msg = R.string.install_confirm_question_no_perms;
}
}
tabHost.setVisibility(View.GONE);
}
if (msg != 0) {
((TextView)findViewById(R.id.install_confirm_question)).setText(msg);
}
mInstallConfirm.setVisibility(View.VISIBLE);
mOk = (Button)findViewById(R.id.ok_button);
mCancel = (Button)findViewById(R.id.cancel_button);
mOk.setOnClickListener(this);
mCancel.setOnClickListener(this);
if (mScrollView == null) {
// There is nothing to scroll view, so the ok button is immediately
// set to install.
mOk.setText(R.string.install);
mOkCanInstall = true;
} else {
mScrollView.setFullScrollAction(new Runnable() {
@Override
public void run() {
mOk.setText(R.string.install);
mOkCanInstall = true;
}
});
}
}
|
diff --git a/stripes/src/net/sourceforge/stripes/tag/InputOptionsEnumerationTag.java b/stripes/src/net/sourceforge/stripes/tag/InputOptionsEnumerationTag.java
index e2012ac..cd9e354 100644
--- a/stripes/src/net/sourceforge/stripes/tag/InputOptionsEnumerationTag.java
+++ b/stripes/src/net/sourceforge/stripes/tag/InputOptionsEnumerationTag.java
@@ -1,132 +1,144 @@
/* Copyright 2005-2006 Tim Fennell
*
* 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.sourceforge.stripes.tag;
import net.sourceforge.stripes.exception.StripesJspException;
import net.sourceforge.stripes.localization.LocalizationUtility;
import net.sourceforge.stripes.util.ReflectUtil;
import net.sourceforge.stripes.util.bean.BeanUtil;
import net.sourceforge.stripes.util.bean.ExpressionException;
import javax.servlet.jsp.JspException;
import java.util.Locale;
/**
* <p>Writes a set of {@literal <option value="foo">bar</option>} tags to the page based on the
* values of a enum. Each value in the enum is represented by a single option tag on the page. The
* options will be generated in ordinal value order (i.e. the order they are declared in the
* enum).</p>
*
* <p>The label (the value the user sees) is generated in one of three ways: by looking up a
* localized value, by using the property named by the 'label' tag attribute if it is supplied
* and lastly by toString()'ing the enumeration value. For example the following tag:</p>
*
*<pre>{@literal <stripes:options-enumeration enum="net.kitty.EyeColor" label="description"/>}</pre>
*
* when generating the option for the value {@code EyeColor.BLUE} will look for a label in the
* following order:</p>
*
* <ul>
* <li>resource: EyeColor.BLUE</li>
* <li>resource: net.kitty.EyeColor.BLUE</li>
* <li>property: EyeColor.BLUE.getDescription() (because of the label="description" above)</li>
* <li>failsafe: EyeColor.BLUE.toString()</li>
* </ul>
*
* <p>If the class specified does not exist, or does not specify a Java 1.5 enum then a
* JspException will be raised.</p>
*
* <p>All attributes of the tag, other than enum and label, are passed directly through to
* the InputOptionTag which is used to generate the individual HTML options tags. As a
* result the InputOptionsEnumerationTag will exhibit the same re-population/selection behaviour
* as the regular options tag.</p>
*
* <p>Since the tag has no use for one it does not allow a body.</p>
*
* @author Tim Fennell
*/
public class InputOptionsEnumerationTag extends InputOptionsCollectionTag {
private String className;
/** Sets the fully qualified name of an enumeration class. */
public void setEnum(String name) {
this.className = name;
}
/** Gets the enum class name set with setEnum(). */
public String getEnum() {
return this.className;
}
/**
* Attempts to instantiate the Class object representing the enum and fetch the values of the
* enum. Then generates an option per value using an instance of an InputOptionTag.
*
* @return SKIP_BODY in all cases.
* @throws JspException if the class name supplied is not a valid class, or cannot be cast
* to Class<Enum>.
*/
public int doStartTag() throws JspException {
Class<Enum> clazz = null;
try {
clazz = (Class<Enum>) ReflectUtil.findClass(this.className);
}
catch (Exception e) {
- throw new StripesJspException
- ("Could not process class [" + this.className + "]. Attribute 'enum' on " +
- "tag options-enumeration must be the fully qualified name of a " +
- "class which is a java 1.5 enum.", e);
+ // Try replacing the last period with a $ just in case the enum in question
+ // is an inner class of another class
+ try {
+ int last = this.className.lastIndexOf('.');
+ if (last > 0) {
+ String n2 = new StringBuilder(className).replace(last, last+1, "$").toString();
+ clazz = ReflectUtil.findClass(n2);
+ }
+ }
+ // If our second attempt didn't work, wrap the *original* exception
+ catch (Exception e2) {
+ throw new StripesJspException
+ ("Could not process class [" + this.className + "]. Attribute 'enum' on " +
+ "tag options-enumeration must be the fully qualified name of a " +
+ "class which is a java 1.5 enum.", e);
+ }
}
if (!clazz.isEnum()) {
throw new StripesJspException
("The class name supplied, [" + this.className + "], does not appear to be " +
"a JDK1.5 enum class.");
}
Enum[] enums = clazz.getEnumConstants();
try {
Locale locale = getPageContext().getRequest().getLocale();
for (Enum item : enums) {
Object value = item.name();
Object label = null;
// Check for a localized label using class.ENUM_VALUE and package.class.ENUM_VALUE
label = LocalizationUtility.getLocalizedFieldName(clazz.getSimpleName() + "." + item.name(),
clazz.getPackage().getName(),
locale);
if (label == null) {
if (getLabel() != null) {
label = BeanUtil.getPropertyValue(getLabel(), item);
}
else {
label = item.toString();
}
}
addEntry(item, label, value);
}
}
catch (ExpressionException ee) {
throw new StripesJspException("A problem occurred generating an options-enumeration. " +
"Most likely either the class [" + getEnum() + "] is not an enum or, [" +
getLabel() + "] is not a valid property of the enum.", ee);
}
return SKIP_BODY;
}
}
| true | true | public int doStartTag() throws JspException {
Class<Enum> clazz = null;
try {
clazz = (Class<Enum>) ReflectUtil.findClass(this.className);
}
catch (Exception e) {
throw new StripesJspException
("Could not process class [" + this.className + "]. Attribute 'enum' on " +
"tag options-enumeration must be the fully qualified name of a " +
"class which is a java 1.5 enum.", e);
}
if (!clazz.isEnum()) {
throw new StripesJspException
("The class name supplied, [" + this.className + "], does not appear to be " +
"a JDK1.5 enum class.");
}
Enum[] enums = clazz.getEnumConstants();
try {
Locale locale = getPageContext().getRequest().getLocale();
for (Enum item : enums) {
Object value = item.name();
Object label = null;
// Check for a localized label using class.ENUM_VALUE and package.class.ENUM_VALUE
label = LocalizationUtility.getLocalizedFieldName(clazz.getSimpleName() + "." + item.name(),
clazz.getPackage().getName(),
locale);
if (label == null) {
if (getLabel() != null) {
label = BeanUtil.getPropertyValue(getLabel(), item);
}
else {
label = item.toString();
}
}
addEntry(item, label, value);
}
}
catch (ExpressionException ee) {
throw new StripesJspException("A problem occurred generating an options-enumeration. " +
"Most likely either the class [" + getEnum() + "] is not an enum or, [" +
getLabel() + "] is not a valid property of the enum.", ee);
}
return SKIP_BODY;
}
| public int doStartTag() throws JspException {
Class<Enum> clazz = null;
try {
clazz = (Class<Enum>) ReflectUtil.findClass(this.className);
}
catch (Exception e) {
// Try replacing the last period with a $ just in case the enum in question
// is an inner class of another class
try {
int last = this.className.lastIndexOf('.');
if (last > 0) {
String n2 = new StringBuilder(className).replace(last, last+1, "$").toString();
clazz = ReflectUtil.findClass(n2);
}
}
// If our second attempt didn't work, wrap the *original* exception
catch (Exception e2) {
throw new StripesJspException
("Could not process class [" + this.className + "]. Attribute 'enum' on " +
"tag options-enumeration must be the fully qualified name of a " +
"class which is a java 1.5 enum.", e);
}
}
if (!clazz.isEnum()) {
throw new StripesJspException
("The class name supplied, [" + this.className + "], does not appear to be " +
"a JDK1.5 enum class.");
}
Enum[] enums = clazz.getEnumConstants();
try {
Locale locale = getPageContext().getRequest().getLocale();
for (Enum item : enums) {
Object value = item.name();
Object label = null;
// Check for a localized label using class.ENUM_VALUE and package.class.ENUM_VALUE
label = LocalizationUtility.getLocalizedFieldName(clazz.getSimpleName() + "." + item.name(),
clazz.getPackage().getName(),
locale);
if (label == null) {
if (getLabel() != null) {
label = BeanUtil.getPropertyValue(getLabel(), item);
}
else {
label = item.toString();
}
}
addEntry(item, label, value);
}
}
catch (ExpressionException ee) {
throw new StripesJspException("A problem occurred generating an options-enumeration. " +
"Most likely either the class [" + getEnum() + "] is not an enum or, [" +
getLabel() + "] is not a valid property of the enum.", ee);
}
return SKIP_BODY;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RetryingPathServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RetryingPathServiceImpl.java
index dea1dfc8b..3f07a22d6 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RetryingPathServiceImpl.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/RetryingPathServiceImpl.java
@@ -1,180 +1,183 @@
/* 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.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.pathparser.BasicPathParser;
import org.opentripplanner.routing.pathparser.PathParser;
import org.opentripplanner.routing.services.GraphService;
import org.opentripplanner.routing.services.PathService;
import org.opentripplanner.routing.services.SPTService;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class RetryingPathServiceImpl implements PathService {
private static final Logger LOG = LoggerFactory.getLogger(RetryingPathServiceImpl.class);
private static final int MAX_TIME_FACTOR = 2;
private static final int MAX_WEIGHT_FACTOR = 2;
@Autowired public GraphService graphService;
@Autowired public SPTService sptService;
private double firstPathTimeout = 0; // seconds
private double multiPathTimeout = 0; // seconds
/** Give up on searching for itineraries after this many seconds have elapsed. */
public void setTimeout (double seconds) {
firstPathTimeout = seconds;
multiPathTimeout = seconds;
}
/**
* Give up on searching for the first itinerary after this many seconds have elapsed.
* A negative or zero value means search forever.
*/
public void setFirstPathTimeout (double seconds) {
firstPathTimeout = seconds;
}
/**
* Stop searching for additional itineraries (beyond the first one) after this many seconds
* have elapsed, relative to the beginning of the search for the first itinerary.
* A negative or zero value means search forever.
* Setting this lower than the firstPathTimeout will avoid searching for additional
* itineraries when finding the first itinerary takes a long time. This helps keep overall
* response time down while assuring that the end user will get at least one response.
*/
public void setMultiPathTimeout (double seconds) {
multiPathTimeout = seconds;
}
@Override
public List<GraphPath> getPaths(RoutingRequest options) {
ArrayList<GraphPath> paths = new ArrayList<GraphPath>();
// make sure the options has a routing context *before* cloning it (otherwise you get
// orphan RoutingContexts leaving temporary edges in the graph until GC)
if (options.rctx == null) {
options.setRoutingContext(graphService.getGraph(options.getRouterId()));
options.rctx.pathParsers = new PathParser[1];
options.rctx.pathParsers[0] = new BasicPathParser();
}
long searchBeginTime = System.currentTimeMillis();
// The list of options specifying various modes, banned routes, etc to try for multiple
// itineraries
Queue<RoutingRequest> optionQueue = new LinkedList<RoutingRequest>();
optionQueue.add(options);
double maxWeight = Double.MAX_VALUE;
double maxWalk = options.getMaxWalkDistance();
long maxTime = options.isArriveBy() ? 0 : Long.MAX_VALUE;
RoutingRequest currOptions;
while (paths.size() < options.numItineraries) {
currOptions = optionQueue.poll();
if (currOptions == null) {
LOG.debug("Ran out of options to try.");
break;
}
currOptions.setMaxWalkDistance(maxWalk);
// apply appropriate timeout
double timeout = paths.isEmpty() ? firstPathTimeout : multiPathTimeout;
// options.worstTime = maxTime;
//options.maxWeight = maxWeight;
long subsearchBeginTime = System.currentTimeMillis();
LOG.debug("BEGIN SUBSEARCH");
ShortestPathTree spt = sptService.getShortestPathTree(currOptions, timeout);
if (spt == null) // timeout or other fail
break;
List<GraphPath> somePaths = spt.getPaths();
LOG.debug("END SUBSEARCH ({} msec of {} msec total)",
System.currentTimeMillis() - subsearchBeginTime,
System.currentTimeMillis() - searchBeginTime);
if (somePaths == null) {
// search failed, likely due to timeout
// this could be signaled with an exception
LOG.warn("Aborting search. {} paths found, elapsed time {} sec",
paths.size(), (System.currentTimeMillis() - searchBeginTime) / 1000.0);
break;
}
- if (maxWeight == Double.MAX_VALUE) {
+ if (maxWeight == Double.MAX_VALUE && maxWalk == Double.MAX_VALUE) {
/* the worst trip we are willing to accept is at most twice as bad or twice as long */
if (somePaths.isEmpty()) {
// if there is no first path, there won't be any other paths
return null;
}
GraphPath path = somePaths.get(0);
long duration = path.getDuration();
LOG.debug("Setting max time and weight for subsequent searches.");
LOG.debug("First path start time: {}", path.getStartTime());
maxTime = path.getStartTime() +
MAX_TIME_FACTOR * (currOptions.isArriveBy() ? -duration : duration);
LOG.debug("First path duration: {}", duration);
LOG.debug("Max time set to: {}", maxTime);
maxWeight = path.getWeight() * MAX_WEIGHT_FACTOR;
LOG.debug("Max weight set to: {}", maxWeight);
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
}
if (somePaths.isEmpty()) {
+ //try again doubling maxwalk
+ maxWalk *= 2;
+ optionQueue.add(currOptions);
LOG.debug("No paths were found.");
continue;
}
for (GraphPath path : somePaths) {
if (!paths.contains(path)) {
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
paths.add(path);
// now, create a list of options, one with each trip in this journey banned.
LOG.debug("New trips: {}", path.getTrips());
RoutingRequest newOptions = currOptions.clone();
for (AgencyAndId trip : path.getTrips()) {
newOptions.bannedTrips.add(trip);
}
if (!optionQueue.contains(newOptions)) {
optionQueue.add(newOptions);
}
}
}
LOG.debug("{} / {} itineraries", paths.size(), currOptions.numItineraries);
}
if (paths.size() == 0) {
return null;
}
// We order the list of returned paths by the time of arrival or departure (not path duration)
Collections.sort(paths, new PathComparator(options.isArriveBy()));
return paths;
}
}
| false | true | public List<GraphPath> getPaths(RoutingRequest options) {
ArrayList<GraphPath> paths = new ArrayList<GraphPath>();
// make sure the options has a routing context *before* cloning it (otherwise you get
// orphan RoutingContexts leaving temporary edges in the graph until GC)
if (options.rctx == null) {
options.setRoutingContext(graphService.getGraph(options.getRouterId()));
options.rctx.pathParsers = new PathParser[1];
options.rctx.pathParsers[0] = new BasicPathParser();
}
long searchBeginTime = System.currentTimeMillis();
// The list of options specifying various modes, banned routes, etc to try for multiple
// itineraries
Queue<RoutingRequest> optionQueue = new LinkedList<RoutingRequest>();
optionQueue.add(options);
double maxWeight = Double.MAX_VALUE;
double maxWalk = options.getMaxWalkDistance();
long maxTime = options.isArriveBy() ? 0 : Long.MAX_VALUE;
RoutingRequest currOptions;
while (paths.size() < options.numItineraries) {
currOptions = optionQueue.poll();
if (currOptions == null) {
LOG.debug("Ran out of options to try.");
break;
}
currOptions.setMaxWalkDistance(maxWalk);
// apply appropriate timeout
double timeout = paths.isEmpty() ? firstPathTimeout : multiPathTimeout;
// options.worstTime = maxTime;
//options.maxWeight = maxWeight;
long subsearchBeginTime = System.currentTimeMillis();
LOG.debug("BEGIN SUBSEARCH");
ShortestPathTree spt = sptService.getShortestPathTree(currOptions, timeout);
if (spt == null) // timeout or other fail
break;
List<GraphPath> somePaths = spt.getPaths();
LOG.debug("END SUBSEARCH ({} msec of {} msec total)",
System.currentTimeMillis() - subsearchBeginTime,
System.currentTimeMillis() - searchBeginTime);
if (somePaths == null) {
// search failed, likely due to timeout
// this could be signaled with an exception
LOG.warn("Aborting search. {} paths found, elapsed time {} sec",
paths.size(), (System.currentTimeMillis() - searchBeginTime) / 1000.0);
break;
}
if (maxWeight == Double.MAX_VALUE) {
/* the worst trip we are willing to accept is at most twice as bad or twice as long */
if (somePaths.isEmpty()) {
// if there is no first path, there won't be any other paths
return null;
}
GraphPath path = somePaths.get(0);
long duration = path.getDuration();
LOG.debug("Setting max time and weight for subsequent searches.");
LOG.debug("First path start time: {}", path.getStartTime());
maxTime = path.getStartTime() +
MAX_TIME_FACTOR * (currOptions.isArriveBy() ? -duration : duration);
LOG.debug("First path duration: {}", duration);
LOG.debug("Max time set to: {}", maxTime);
maxWeight = path.getWeight() * MAX_WEIGHT_FACTOR;
LOG.debug("Max weight set to: {}", maxWeight);
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
}
if (somePaths.isEmpty()) {
LOG.debug("No paths were found.");
continue;
}
for (GraphPath path : somePaths) {
if (!paths.contains(path)) {
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
paths.add(path);
// now, create a list of options, one with each trip in this journey banned.
LOG.debug("New trips: {}", path.getTrips());
RoutingRequest newOptions = currOptions.clone();
for (AgencyAndId trip : path.getTrips()) {
newOptions.bannedTrips.add(trip);
}
if (!optionQueue.contains(newOptions)) {
optionQueue.add(newOptions);
}
}
}
LOG.debug("{} / {} itineraries", paths.size(), currOptions.numItineraries);
}
if (paths.size() == 0) {
return null;
}
// We order the list of returned paths by the time of arrival or departure (not path duration)
Collections.sort(paths, new PathComparator(options.isArriveBy()));
return paths;
}
| public List<GraphPath> getPaths(RoutingRequest options) {
ArrayList<GraphPath> paths = new ArrayList<GraphPath>();
// make sure the options has a routing context *before* cloning it (otherwise you get
// orphan RoutingContexts leaving temporary edges in the graph until GC)
if (options.rctx == null) {
options.setRoutingContext(graphService.getGraph(options.getRouterId()));
options.rctx.pathParsers = new PathParser[1];
options.rctx.pathParsers[0] = new BasicPathParser();
}
long searchBeginTime = System.currentTimeMillis();
// The list of options specifying various modes, banned routes, etc to try for multiple
// itineraries
Queue<RoutingRequest> optionQueue = new LinkedList<RoutingRequest>();
optionQueue.add(options);
double maxWeight = Double.MAX_VALUE;
double maxWalk = options.getMaxWalkDistance();
long maxTime = options.isArriveBy() ? 0 : Long.MAX_VALUE;
RoutingRequest currOptions;
while (paths.size() < options.numItineraries) {
currOptions = optionQueue.poll();
if (currOptions == null) {
LOG.debug("Ran out of options to try.");
break;
}
currOptions.setMaxWalkDistance(maxWalk);
// apply appropriate timeout
double timeout = paths.isEmpty() ? firstPathTimeout : multiPathTimeout;
// options.worstTime = maxTime;
//options.maxWeight = maxWeight;
long subsearchBeginTime = System.currentTimeMillis();
LOG.debug("BEGIN SUBSEARCH");
ShortestPathTree spt = sptService.getShortestPathTree(currOptions, timeout);
if (spt == null) // timeout or other fail
break;
List<GraphPath> somePaths = spt.getPaths();
LOG.debug("END SUBSEARCH ({} msec of {} msec total)",
System.currentTimeMillis() - subsearchBeginTime,
System.currentTimeMillis() - searchBeginTime);
if (somePaths == null) {
// search failed, likely due to timeout
// this could be signaled with an exception
LOG.warn("Aborting search. {} paths found, elapsed time {} sec",
paths.size(), (System.currentTimeMillis() - searchBeginTime) / 1000.0);
break;
}
if (maxWeight == Double.MAX_VALUE && maxWalk == Double.MAX_VALUE) {
/* the worst trip we are willing to accept is at most twice as bad or twice as long */
if (somePaths.isEmpty()) {
// if there is no first path, there won't be any other paths
return null;
}
GraphPath path = somePaths.get(0);
long duration = path.getDuration();
LOG.debug("Setting max time and weight for subsequent searches.");
LOG.debug("First path start time: {}", path.getStartTime());
maxTime = path.getStartTime() +
MAX_TIME_FACTOR * (currOptions.isArriveBy() ? -duration : duration);
LOG.debug("First path duration: {}", duration);
LOG.debug("Max time set to: {}", maxTime);
maxWeight = path.getWeight() * MAX_WEIGHT_FACTOR;
LOG.debug("Max weight set to: {}", maxWeight);
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
}
if (somePaths.isEmpty()) {
//try again doubling maxwalk
maxWalk *= 2;
optionQueue.add(currOptions);
LOG.debug("No paths were found.");
continue;
}
for (GraphPath path : somePaths) {
if (!paths.contains(path)) {
if (path.getWalkDistance() > maxWalk) {
maxWalk = path.getWalkDistance() * 1.25;
}
paths.add(path);
// now, create a list of options, one with each trip in this journey banned.
LOG.debug("New trips: {}", path.getTrips());
RoutingRequest newOptions = currOptions.clone();
for (AgencyAndId trip : path.getTrips()) {
newOptions.bannedTrips.add(trip);
}
if (!optionQueue.contains(newOptions)) {
optionQueue.add(newOptions);
}
}
}
LOG.debug("{} / {} itineraries", paths.size(), currOptions.numItineraries);
}
if (paths.size() == 0) {
return null;
}
// We order the list of returned paths by the time of arrival or departure (not path duration)
Collections.sort(paths, new PathComparator(options.isArriveBy()));
return paths;
}
|
diff --git a/src/org/vesalainen/parser/ParserFactory.java b/src/org/vesalainen/parser/ParserFactory.java
index 555163f..058095e 100644
--- a/src/org/vesalainen/parser/ParserFactory.java
+++ b/src/org/vesalainen/parser/ParserFactory.java
@@ -1,176 +1,176 @@
/*
* Copyright (C) 2012 Timo Vesalainen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.vesalainen.grammar.Grammar;
import org.vesalainen.parser.annotation.GenClassname;
/**
* Helper class for getting instances of parser classes. Uses @GenClassname annotation
* to detect implementation class name.
* @version $Id$
* @author tkv
*/
public class ParserFactory
{
private static Map<Class<?>,Class<?>> map = new HashMap<>();
/**
* Creates parser class instance either by using ClassLoader or by compiling it dynamically
* @param cls Annotated class acting also as superclass for created parser
* @return
* @throws ParserException
*/
public static Object getParserInstance(Class<?> cls) throws ParserException
{
return getParserInstance(cls, false);
}
public static Object getParserInstance(Class<?> cls, boolean debug) throws ParserException
{
return getParserInstance(cls, null, debug);
}
/**
* Creates parser class instance either by using ClassLoader or by compiling it dynamically
* @param cls Class acting as superclass for created parser
* @param grammar Used Grammar
* @return
* @throws ParserException
*/
public static Object getParserInstance(Class<?> cls, Grammar grammar) throws ParserException
{
return getParserInstance(cls, grammar, false);
}
public static Object getParserInstance(Class<?> cls, Grammar grammar, boolean debug) throws ParserException
{
Class<?> parserClass = getParserClass(cls, grammar, debug);
try
{
return parserClass.newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
throw new ParserException(ex);
}
}
/**
* Creates parser class either by using ClassLoader or by compiling it dynamically
* @param cls Annotated class acting also as superclass for created parser
* @return
* @throws ParserException
*/
public static Class<?> getParserClass(Class<?> cls) throws ParserException
{
return getParserClass(cls, false);
}
public static Class<?> getParserClass(Class<?> cls, boolean debug) throws ParserException
{
return getParserClass(cls, null, debug);
}
/**
* Creates parser class either by using ClassLoader or by compiling it dynamically
* @param cls Class acting as superclass for created parser
* @param grammar Used Grammar
* @return
* @throws ParserException
*/
public static Class<?> getParserClass(Class<?> cls, Grammar grammar) throws ParserException
{
return getParserClass(cls, grammar, false);
}
public static Class<?> getParserClass(Class<?> cls, Grammar grammar, boolean debug) throws ParserException
{
try
{
return loadParserClass(cls);
}
catch (ClassNotFoundException ex)
{
try
{
ParserCompiler pc = null;
if (grammar == null)
{
pc = new ParserCompiler(cls);
pc.compile();
}
else
{
pc = new ParserCompiler(cls, grammar);
pc.compile();
}
return pc.loadDynamic();
}
catch (ReflectiveOperationException | IOException ex1)
{
- throw new ParserException(ex);
+ throw new ParserException(ex1);
}
}
}
/**
* Creates parser class instance by using ClassLoader. Return null if unable to
* load class
* @param cls Annotated class acting also as superclass for created parser
* @return
* @throws ParserException
*/
public static Object loadParserInstance(Class<?> cls) throws ParserException
{
try
{
Class<?> parserClass;
try
{
parserClass = loadParserClass(cls);
}
catch (ClassNotFoundException ex)
{
return null;
}
return parserClass.newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
throw new ParserException(ex);
}
}
/**
* Creates parser class by using ClassLoader. Return null if unable to
* load class
* @param cls Annotated class acting also as superclass for created parser
* @return
* @throws ClassNotFoundException
*/
public static Class<?> loadParserClass(Class<?> cls) throws ClassNotFoundException
{
Class<?> parserClass = map.get(cls);
if (parserClass == null)
{
GenClassname genClassname = cls.getAnnotation(GenClassname.class);
if (genClassname == null)
{
throw new IllegalArgumentException("@GenClassname not set in "+cls);
}
parserClass = Class.forName(genClassname.value());
map.put(cls, parserClass);
}
return parserClass;
}
}
| true | true | public static Class<?> getParserClass(Class<?> cls, Grammar grammar, boolean debug) throws ParserException
{
try
{
return loadParserClass(cls);
}
catch (ClassNotFoundException ex)
{
try
{
ParserCompiler pc = null;
if (grammar == null)
{
pc = new ParserCompiler(cls);
pc.compile();
}
else
{
pc = new ParserCompiler(cls, grammar);
pc.compile();
}
return pc.loadDynamic();
}
catch (ReflectiveOperationException | IOException ex1)
{
throw new ParserException(ex);
}
}
}
| public static Class<?> getParserClass(Class<?> cls, Grammar grammar, boolean debug) throws ParserException
{
try
{
return loadParserClass(cls);
}
catch (ClassNotFoundException ex)
{
try
{
ParserCompiler pc = null;
if (grammar == null)
{
pc = new ParserCompiler(cls);
pc.compile();
}
else
{
pc = new ParserCompiler(cls, grammar);
pc.compile();
}
return pc.loadDynamic();
}
catch (ReflectiveOperationException | IOException ex1)
{
throw new ParserException(ex1);
}
}
}
|
diff --git a/x10.compiler/src/x10/optimizations/ForLoopOptimizer.java b/x10.compiler/src/x10/optimizations/ForLoopOptimizer.java
index ecb257a9e..c1ace173e 100644
--- a/x10.compiler/src/x10/optimizations/ForLoopOptimizer.java
+++ b/x10.compiler/src/x10/optimizations/ForLoopOptimizer.java
@@ -1,1256 +1,1256 @@
/*
* 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.optimizations;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import polyglot.ast.Assign;
import polyglot.ast.Binary;
import polyglot.ast.Block;
import polyglot.ast.BooleanLit;
import polyglot.ast.Branch;
import polyglot.ast.Call;
import polyglot.ast.Expr;
import polyglot.ast.Field;
import polyglot.ast.For;
import polyglot.ast.ForInit;
import polyglot.ast.ForUpdate;
import polyglot.ast.Formal;
import polyglot.ast.Id;
import polyglot.ast.IntLit;
import polyglot.ast.Local;
import polyglot.ast.LocalDecl;
import polyglot.ast.Loop;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.Receiver;
import polyglot.ast.Stmt;
import polyglot.ast.Switch;
import polyglot.ast.Term;
import polyglot.ast.TypeNode;
import polyglot.ast.Unary;
import polyglot.ast.Assign.Operator;
import polyglot.frontend.Job;
import polyglot.types.Context;
import polyglot.types.Flags;
import polyglot.types.LocalDef;
import polyglot.types.LocalInstance;
import polyglot.types.Name;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.types.Types;
import polyglot.util.InternalCompilerError;
import polyglot.util.Position;
import polyglot.visit.ContextVisitor;
import polyglot.visit.NodeVisitor;
import x10.ast.ClosureCall;
import x10.ast.ForLoop;
import x10.ast.ForLoop_c;
import x10.ast.RegionMaker;
import x10.ast.StmtExpr;
import x10.ast.StmtSeq;
import x10.ast.X10Call;
import x10.ast.X10Cast;
import x10.ast.X10Formal;
import x10.constraint.XFailure;
import x10.constraint.XTerm;
import polyglot.types.Context;
import x10.types.X10FieldInstance;
import x10.types.X10MethodInstance;
import x10.types.X10TypeMixin;
import polyglot.types.TypeSystem;
import x10.types.X10TypeSystem_c;
import x10.types.checker.Converter;
import x10.types.constraints.CConstraint;
import x10.util.Synthesizer;
import x10.visit.ConstantPropagator;
/**
* Optimize loops of the form: for (formal in domain) S.
* If domain is, or can be lowered to, a Region, that is rectangular with know rank,
* tranform into a nest of traditional for-loops with iterates of type int.
*
* @author vj
* @author Bowen Alpern
*/
public class ForLoopOptimizer extends ContextVisitor {
private static final Name ITERATOR = Name.make("iterator");
private static final Name HASNEXT = Name.make("hasNext");
private static final Name REGION = Name.make("region");
private static final Name DIST = Name.make("dist");
private static final Name NEXT = Name.make("next");
private static final Name MAKE = Name.make("make");
private static final Name RANK = Name.make("rank");
private static final Name MIN = Name.make("min");
private static final Name MAX = Name.make("max");
private static final Name SET = Name.make("set");
private final TypeSystem xts;
private final NodeFactory xnf;
private final Synthesizer syn;
public ForLoopOptimizer(Job job, TypeSystem ts, NodeFactory nf) {
super(job, ts, nf);
xts = (TypeSystem) ts;
xnf = (NodeFactory) nf;
syn = new Synthesizer(xnf, xts);
}
public Node leaveCall(Node old, Node n, NodeVisitor v) throws SemanticException {
if (n instanceof ForLoop)
return visitForLoop((ForLoop_c) n);
return n;
}
private static final boolean VERBOSE = false;
/**
* Transform a ForLoop with a Point iterate over a rectangular region to a nest of simple For loops.
* <pre>
* for (p:Point(k+1) in r) S ->
* { // k=r.rank-1
* point = Rail.make[Int](k+1); // if p is named
* mink=r.min(k); maxk=r.max(k);
* ...
* min0=r.min(0); max0=r.max(0);
* for (i0 = min0; i0<=max0; i0+=1) {
* point(0) = i0; // if p is named
* ...
* for (ik = mink; ik<=maxk; ik+=1) {
* point(k) = ik; // if p is named
* p = Point.make(point); // if p is named
* S
* }
* }
* }
* </pre>
* <tt>r</tt> can be an Array, a DistArray, a Dist, or a Region.
*
* Also, desugars untransformed ForLoops, TODO: move this to the desugarer
* <pre>
* for (x in y) S -> for (i=y.iterator(); i.hasNext(); ) { x=i.next(); S }
* </pre>
*
* @param loop the ForLoop to be transformed
* @return the transformed loop
*/
public Node visitForLoop(ForLoop_c loop) {
Position pos = loop.position();
X10Formal formal = (X10Formal) loop.formal();
Expr domain = loop.domain();
Stmt body = loop.body();
if (VERBOSE) {
System.out.println("\nOptimizing ForLoop at " +pos);
loop.prettyPrint(System.out);
System.out.println();
}
// if domain <: DistArray, transform to Distribution
if (xts.isX10DistArray(domain.type())) {
if (VERBOSE) System.out.println(" domain is DistArray, tranforming to Dist");
domain = createFieldRef(pos, domain, DIST);
assert (null != domain);
}
// if domain <: Distribution, transform to Region
if (((X10TypeSystem_c) xts).isDistribution(domain.type())) {
if (VERBOSE) System.out.println(" domain is Dist, transforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
// if domain <: Array, transform to Region
if (xts.isX10Array(domain.type())) {
if (VERBOSE) System.out.println(" domain is Array, tranforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
Id label = createLabel(pos);
Context context = (Context) context();
List<Formal> formalVars = formal.vars();
boolean named = !formal.isUnnamed();
boolean isRect = X10TypeMixin.isRect(domain.type(), context);
Integer domainRank = (Integer) getPropertyConstantValue(domain, RANK);
int rank = (null != domainRank) ? (int) domainRank :
(null != formalVars) ? formalVars.size() :
-1;
assert null == formalVars || formalVars.isEmpty() || formalVars.size() == rank;
// SPECIAL CASE (XTENLANG-1340):
// for (p(i) in e1..e2) S =>
// val min=e1; val max=e2; for(var z:Int=min; z<=max; z++){ val p=Point.make(z); val i=z; S }
// TODO inline (min and max), scalar replace Region object and its constituent Arrays then delete this code
//
if (1 == rank && domain instanceof RegionMaker) {
List<Expr> args = ((RegionMaker) loop.domain()).arguments();
assert (args.size() == 2);
Expr low = args.get(0);
Expr high = args.get(1);
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh("i")
: Name.makeFresh(formalVars.get(0).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, low);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, high);
- LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, createLocal(pos, minLDecl));
+ LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, xts.Int(), createLocal(pos, minLDecl));
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (named) {
// declare the formal variable as a local and initialize it
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, varLDecl));
LocalDecl formalLDecl = transformFormalToLocalDecl(formal, formExpr);
bodyStmts.add(formalLDecl);
}
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(0), createLocal(pos, varLDecl)));
}
bodyStmts.add(body);
body = createBlock(loop.body().position(), bodyStmts);
For forLoop = createStandardFor(pos, varLDecl, cond, update, body);
return createBlock(pos, minLDecl, maxLDecl, forLoop);
}
// transform rectangular regions of known rank
if (xts.isRegion(domain.type()) && isRect && rank > 0) {
assert xts.isPoint(formal.declType());
if (VERBOSE) System.out.println(" rectangular region, rank=" +rank+ " point=" +formal);
if (1 < rank) {
body = labelFreeBreaks(body, label);
}
List<Stmt> stmts = new ArrayList<Stmt>();
Name prefix = named ? formal.name().id() : Name.make("p");
// cache the value of domain in a local temporary variable
LocalDecl domLDecl = createLocalDecl(domain.position(), Flags.FINAL, Name.makeFresh(prefix), domain);
stmts.add(domLDecl);
// Prepare to redeclare the formal iterate as local Point variable (if the formal is not anonymous)
Type indexType = null; // type of the formal var initializer (if any)
LocalDecl indexLDecl = null; // redeclaration of the formal var (if it has a name)
if (named) {
// create a rail to contain the value of the formal at each iteration
Name indexName = Name.makeFresh(prefix);
indexType = xts.Rail(xts.Int()); // PlaceChecker.AddIsHereClause(xts.Rail(xts.Int()), context);
List<Type> railType = Collections.<Type>singletonList(xts.Int());
Expr indexInit = createStaticCall(pos, xts.Rail(), MAKE, railType, createIntLit(rank));
indexLDecl = createLocalDecl(pos, Flags.FINAL, indexName, indexType, indexInit);
// add the declaration of the index rail to the list of statements to be executed before the loop nest
stmts.add(indexLDecl);
}
LocalDecl varLDecls[] = new LocalDecl[rank];
// create the loop nest (from the inside out)
for (int r=rank-1; 0<=r; r--) {
// create new names for the r-th iterate and limits
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh(prefix)
: Name.makeFresh(formalVars.get(r).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
// create an AST node for the calls to domain.min() and domain.max()
Expr minVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MIN, createIntLit(r));
Expr maxVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MAX, createIntLit(r));
// create an AST node for the declaration of the temporary locations for the r-th var, min, and max
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, minVal);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, maxVal);
- LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, createLocal(pos, minLDecl));
+ LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, xts.Int(), createLocal(pos, minLDecl));
varLDecls[r] = varLDecl;
// add the declarations for the r-th min and max to the list of statements to be executed before the loop nest
stmts.add(minLDecl);
stmts.add(maxLDecl);
// create expressions for the second and third positions in the r-th for clause
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(r), createLocal(pos, varLDecl)));
}
// concoct declaration for formal, in case it might be referenced in the body
if (named) {
// set the r-th slot int the index rail to the current value of the r-th iterate
Expr setExpr = createInstanceCall( pos,
createLocal(pos, indexLDecl),
SET,
createLocal(pos, varLDecl),
createIntLit(r) );
bodyStmts.addAll(convertToStmtList(setExpr));
if (r+1 == rank) { // the innermost loop
// declare the formal variable as a local and initialize it to the index rail
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, indexLDecl));
bodyStmts.add(transformFormalToLocalDecl(formal, formExpr));
}
}
bodyStmts.add(body);
body = createBlock(pos, bodyStmts);
// create the AST node for the r-th concocted for-statement
body = createStandardFor(pos, varLDecl, cond, update, body);
}
if (1 < rank) {
body = xnf.Labeled(body.position(), label, body);
}
body = explodePoint(formal, indexLDecl, varLDecls, body);
stmts.add(body);
Block result = createBlock(pos, stmts);
if (VERBOSE) result.dump(System.out);
return result;
}
assert (xts.isSubtype(domain.type(), xts.Iterable(xts.Any()), context));
Name iterName = named ? Name.makeFresh(formal.name().id()) : Name.makeFresh();
Expr iterInit = createInstanceCall(pos, domain, ITERATOR);
LocalDecl iterLDecl = createLocalDecl(pos, Flags.FINAL, iterName, iterInit);
Expr hasExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), HASNEXT);
Expr nextExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), NEXT);
if (!xts.typeEquals(nextExpr.type(), formal.declType(), context)) {
Expr newNextExpr = createCoercion(pos, nextExpr, formal.declType());
if (null == newNextExpr)
throw new InternalCompilerError("Unable to cast "+nextExpr+" to the iterated type "+formal.declType(), pos);
nextExpr = newNextExpr;
}
List<Stmt> bodyStmts = new ArrayList<Stmt>();
LocalDecl varLDecl = transformFormalToLocalDecl(formal, nextExpr);
bodyStmts.add(varLDecl);
if (null != formalVars && !formalVars.isEmpty()) try {
bodyStmts.addAll(formal.explode(this));
} catch (SemanticException e) {
throw new InternalCompilerError("We cannot explode the formal. Huh?", formal.position(), e);
}
if (body instanceof Block) {
bodyStmts.addAll(((Block) body).statements());
} else {
bodyStmts.add(body);
}
Stmt result = createStandardFor(pos, iterLDecl, hasExpr, createBlock(pos, bodyStmts));
if (VERBOSE) result.dump(System.out);
return result;
}
/**
* Replace calls to the apply method on point with corresponding calls to the corresponding method on rail throughout the body
*
* @param point a Point formal variable
* @param rail the underlying Rail defining point
* @param body the AST containing the usses of point to be replaced
* @return a copy of body with every call to point.apply() replaced by a call to rail.apply()
*/
private Stmt explodePoint(final X10Formal point, final LocalDecl rail, final LocalDecl[] indices, final Stmt body) {
ContextVisitor pointExploder = new ContextVisitor(job, xts, xnf) {
/* (non-Javadoc)
* @see polyglot.visit.ErrorHandlingVisitor#leaveCall(polyglot.ast.Node)
*/
@Override
protected Node leaveCall(Node n) throws SemanticException {
if (n instanceof Call) {
X10Formal p = point;
LocalDecl r = rail;
LocalDecl[] is = indices;
Call call = (Call) n;
Receiver target = call.target();
if (target instanceof Local && call.methodInstance().name().equals(ClosureCall.APPLY)) {
if (((Local) target).localInstance().def() == point.localDef()) {
List<Expr> args = call.arguments();
assert (1 == args.size());
Expr arg = args.get(0);
if (arg.isConstant()) {
int i =(Integer) arg.constantValue();
return syn.createLocal(n.position(), indices[i]);
}
call = call.target(createLocal(target.position(), rail));
call = call.methodInstance(createMethodInstance( rail.type().type(),
ClosureCall.APPLY,
Collections.<Type>emptyList(),
call.methodInstance().formalTypes()));
return call;
}
}
}
return n;
}
};
return (Stmt) body.visit(pointExploder.begin());
}
/**
* Change free unlabeled breaks in the body to refer to a given label.
*
* @param body the body of a ForLoop
* @param label a label to be attached to the outermost synthesized For
* @return aa copy of the body with its free breaks suitably captured
*/
private Stmt labelFreeBreaks(Stmt body, final Id label) {
return (Stmt) body.visit(new NodeVisitor(){
@Override
public Node override(Node node) { // these constructs capture free breaks
if (node instanceof Loop) return node;
if (node instanceof Switch) return node;
return null;
}
@Override
public Node leave(Node old, Node n, NodeVisitor v) {
if (n instanceof Branch) {
Branch b = (Branch) n;
if (b.kind().equals(Branch.BREAK) && null == b.labelNode()) {
return b.labelNode(label);
}
}
return n;
}
});
}
/**
* @param pos
* @return
*/
private Id createLabel(Position pos) {
Id label = xnf.Id(pos, Name.makeFresh("L"));
return label;
}
// General helper methods
/**
* Obtain the constant value of a property of an expression, if that value is known at compile time.
*
* @param expr the Expr whose property is to be extracted
* @param name the Name of the property to extract
* @return the value of the named property of expr if it is a compile-time constant, or null if none
* TODO: move into ASTQuery
*/
public Object getPropertyConstantValue(Expr expr, Name name) {
X10FieldInstance propertyFI = X10TypeMixin.getProperty(expr.type(), name);
if (null == propertyFI) return null;
Expr propertyExpr = createFieldRef(expr.position(), expr, propertyFI);
if (null == propertyExpr) return null;
return ConstantPropagator.constantValue(propertyExpr);
}
/**
* Add a constraint to the type that binds a given property to a given value.
*
* @param type the Type to be constrained
* @param name the Name of a property of type
* @param value the value of the named property for this type
* @return the type with the additional constraint {name==value}, or null if no such property
* TODO: move into Synthesizer
*/
public static Type addPropertyConstraint(Type type, Name name, XTerm value) throws XFailure {
XTerm property = X10TypeMixin.findOrSynthesize(type, name);
if (null == property) return null;
return X10TypeMixin.addBinding(type, property, value);
}
/**
* Add a constraint to the type that binds a given property to a given value.
*
* @param type the Type to be constrained
* @param name the Name of a property of type
* @param value the value of the named property for this type
* @return the type with the additional constraint {name==value}, or null if no such property
* TODO: move into Synthesizer
*/
/* public static Type addPropertyConstraint(Type type, Name name, Object value) {
return addPropertyConstraint(type, name, XTerms.makeLit(value));
}*/
/**
* Add a self constraint to the type that binds self to a given value.
*
* @param type the Type to be constrained
* @param value the value of self for this type
* @return the type with the additional constraint {self==value}, or null if the proposed
* binding is inconsistent
* TODO: move into Synthesizer
*/
public static Type addSelfConstraint(Type type, XTerm value) {
try {
return X10TypeMixin.addSelfBinding(type, value);
} catch (XFailure e) {
return null;
}
}
// helper methods that build AST Nodes
// These methods could move into the X10 Synthesizer.
// helper method that create subclasses of Stmt
/**
* Turn a formal parameter into local variable declaration.
*
* @param formal the parameter to be transformed
* @param init an expression representing the initial value of new local variable
* @return the declaration for a local variable with the same behavior as formal
* TODO: move into Synthesizer
*/
public LocalDecl transformFormalToLocalDecl(X10Formal formal, Expr init) {
return xnf.LocalDecl(formal.position(), formal.flags(), formal.type(), formal.name(), init).localDef(formal.localDef());
}
/**
* Create a declaration for a local variable from a local type definition.
*
* @param pos the Position of the declaration
* @param def the definition of the declared local variable
* @param init the Expr representing the initial value of the declared local variable
* @return the LocalDecl representing the declaration of the local variable
* TODO: move into Synthesizer
*/
public LocalDecl createLocalDecl(Position pos, LocalDef def, Expr init) {
return xnf.LocalDecl( pos.markCompilerGenerated(),
xnf.FlagsNode(pos, def.flags()),
xnf.CanonicalTypeNode(pos, def.type().get()),
xnf.Id(pos, def.name()),
init ).localDef(def);
}
/**
* Create a declaration for a local variable from scratch.
* (A local variable definition is created as a side-effect and may be retrieved from the result.)
*
* @param pos the Position of the declaration
* @param flags the Flags ("static", "public", "var") for the declared local variable
* @param name the Name of the declared local variable
* @param type the Type of the declared local variable
* @param init an Expr representing the initial value of the declared local variable
* @return the LocalDecl representing the declaration of the local variable
* TODO: move into Synthesizer
*/
public LocalDecl createLocalDecl(Position pos, Flags flags, Name name, Type type, Expr init) {
LocalDef def = xts.localDef(pos, flags, Types.ref(type), name);
return createLocalDecl(pos, def, init);
}
/**
* Create a declaration for a local variable using the type of the initializer.
*
* @param pos the Position of the declaration
* @param flags the Flags ("static", "public", "var") for the declared local variable
* @param name the Name of the declared local variable
* @param init an Expr representing the initial value of the declared local variable
* @return the LocalDecl representing the declaration of the local variable
* TODO: move into Synthesizer
*/
public LocalDecl createLocalDecl(Position pos, Flags flags, Name name, Expr init) {
if (init.type().isVoid()) {
System.err.println("ERROR: ForLoopOptimizer.createLocalDecl: creating void local assignment for " +init+ " at " +pos);
}
return createLocalDecl(pos, flags, name, init.type(), init);
}
/**
* Create a traditional C-style 'for' loop.
* This form assumes that the update part of the for header is empty.
*
* @param pos the Position of the loop is the source program
* @param init the declaration that initializes the iterate
* @param cond the condition governing whether the body should continue to be executed
* @param body the body of the loop to be executed repeatedly
* @return the synthesized 'for' loop
* TODO: move into Synthesizer
*/
public For createStandardFor(Position pos, LocalDecl init, Expr cond, Stmt body) {
return xnf.For( pos,
Collections.<ForInit>singletonList(init),
cond,
Collections.<ForUpdate>emptyList(),
body );
}
/**
* Create a traditional C-style 'for' loop.
*
* @param pos the Position of the loop is the source program
* @param init the declaration that initializes the iterate
* @param cond the condition governing whether the body should continue to be executed
* @param update the statement to increment the iterate after each execution of the body
* @param body the body of the loop to be executed repeatedly
* @return the synthesized for-loop
* TODO: move into Synthesizer
*/
public For createStandardFor(Position pos, LocalDecl init, Expr cond, Expr update, Stmt body) {
return xnf.For( pos,
Collections.<ForInit>singletonList(init),
cond,
Collections.<ForUpdate>singletonList(xnf.Eval(pos, update)),
body );
}
/**
* Create a block of statements from a list.
*
* @param pos the Position of the block in the source code
* @param stmts the Stmt's to be included in the block
* @return the synthesized Block
* TODO: move into Synthesizer
*/
public Block createBlock(Position pos, List<Stmt> stmts) {
return xnf.Block(pos, stmts);
}
/**
* Create a block of statements from individual terms (statements and/or expressions).
* If a term is already a Stmt, it is used as is.
* If it is an Expr, the Stmt is its evaluation.
* Otherwise an InvalidArgumentException is thrown.
*
* @param pos the Position of the block in the source code
* @param terms the sequence of terms to become statements of the block
* @return the synthesized Block of terms turned to statements
* @throws IllegalArgumentException if one of the terms is not a Stmt or an Expr
* TODO: move into Synthesizer
*/
public Block createBlock(Position pos, Term... terms) {
return createBlock(pos, convertToStmtList(terms));
}
/**
* Convert individual terms (statements and/or expressions) to a list of statements.
* If a term is already a Stmt, it is used as is.
* If it is an Expr, the Stmt is its evaluation.
* Otherwise an InvalidArgumentException is thrown.
*
* @param terms the sequence of terms
* @return the newly constructed list of statements
* @throws IllegalArgumentException if one of the terms is not a Stmt or an Expr
* TODO: move into Synthesizer
*/
public List<Stmt> convertToStmtList(Term... terms) {
List<Stmt> stmts = new ArrayList<Stmt> (terms.length);
for (Term term : terms) {
if (term instanceof Expr) {
term = xnf.Eval(term.position(), (Expr) term);
} else if (!(term instanceof Stmt)) {
throw new IllegalArgumentException("Invalid argument type: "+term.getClass());
}
stmts.add((Stmt) term);
}
return stmts;
}
/**
* Create a break statement.
*
* @param pos the Position of the break statement in source code
* @return the synthesized break statement
* TODO: move to Synthesizer
*/
public Branch createBreak(Position pos) {
return xnf.Break(pos);
}
/**
* Create a declaration for an uninitialized local variable from scratch.
* (A local variable definition is created as a side-effect and may be retrieved from the result.)
*
* @param pos the Position of the declaration
* @param flags the Flags ("static", "public", "var") for the declared local variable
* @param name the Name of the declared local variable
* @param type the Type of the declared local variable
* @return the LocalDecl representing the declaration of the local variable
* TODO: move into Synthesizer
*/
public LocalDecl createLocalDecl(Position pos, Flags flags, Name name, Type type) {
LocalDef def = xts.localDef(pos, flags, Types.ref(type), name);
return createLocalDecl(pos, def);
}
/**
* Create a declaration for a local variable from an uninitialized local type definition.
*
* @param pos the Position of the declaration
* @param def the definition of the declared local variable
* @return the LocalDecl representing the declaration of the local variable
* TODO: move into Synthesizer
*/
public LocalDecl createLocalDecl(Position pos, LocalDef def) {
return xnf.LocalDecl( pos,
xnf.FlagsNode(pos, def.flags()),
xnf.CanonicalTypeNode(pos, def.type().get()),
xnf.Id(pos, def.name()) ).localDef(def);
}
/**
* Create an assignment statement.
*
* @param pos the Position of the assignment in source code
* @param target the left-hand side of the assignment
* @param op the assignment operator
* @param source the right-hand side of the assignment
* @return the synthesized assignment statement
* TODO: move to synthesizer
*/
public Stmt createAssignment(Position pos, Expr target, Operator op, Expr source) {
return createAssignment(createAssign(pos, target, op, source));
}
/**
* Create as assignment statement for a given Assign expression.
*
* @param expr the expression to evaluate
* @return the synthesized assignment statement
* TODO: move to Synthesizer
*/
public Stmt createAssignment(Assign expr) {
return createEval(expr);
}
/**
* Create an evaluation statement for a given expression.
*
* @param expr the expression to be evaluated
* @return a synthesized statement that evaluates expr
* TODO: move to Synthesizer
*/
public Stmt createEval(Expr expr) {
return xnf.Eval(expr.position(), expr);
}
/**
* Create a conditional statements.
*
* @param pos the Position of the conditional statement in source code.
* @param cond the boolean expression to be tested
* @param thenStmt the statement to execute if cond is true
* @param elseStmt the statement to execute if cond is false
* @return the synthesized conditional statement
* TODO: move to Synthesizer
*/
public Stmt createIf(Position pos, Expr cond, Stmt thenStmt, Stmt elseStmt) {
if (null == elseStmt) return xnf.If(pos, cond, thenStmt);
return xnf.If(pos, cond, thenStmt, elseStmt);
}
/**
* Turn a single statement into a statement sequence.
*
* @param stmt the statement to be encapsulated
* @return a synthesized statement sequence comprising stmt
*/
public StmtSeq toStmtSeq(Stmt stmt) {
return toStmtSeq(stmt.position(), Collections.singletonList(stmt));
}
/**
* Turn a list of statements into a statement sequence.
*
* @param pos the Position of the statement sequence in source code
* @param stmts a list of statements
* @return a synthesized statement sequence comprising stmts
* TODO: move to Synthesizer
*/
public StmtSeq toStmtSeq(Position pos, List<Stmt> stmts) {
return xnf.StmtSeq(pos, stmts);
}
// helper methods that create subclasses of Expr
/**
* Create a statement expression -- a block of statements with a result value.
*
* @param pos the Position of the statement expression in source code
* @param stmts the statements to proceed evaluation of expr
* @param expr the result of the statement expression
* @return a synthesized statement expresssion comprising stmts and expr
* TODO: move to Synthesizer
*/
public StmtExpr createStmtExpr(Position pos, List<Stmt> stmts, Expr expr) {
if (null == expr) return (StmtExpr) xnf.StmtExpr(pos, stmts, null).type(xts.Void());
return (StmtExpr) xnf.StmtExpr(pos, stmts, expr).type(expr.type());
}
/**
* Create an IntLit node representing a given integer literal.
*
* @param val the int value to be represented
* @return an IntLit node representing the literal integer val
* TODO: move into Synthesizer
*/
public IntLit createIntLit(int val) {
try {
return (IntLit) xnf.IntLit(Position.COMPILER_GENERATED, IntLit.INT, val).typeCheck(this);
} catch (SemanticException e) {
throw new InternalCompilerError("Int literal with value "+val+" would not typecheck", e);
}
}
/**
* Create the boolean literal "true".
*
* @param pos the Position of the literal in source code
* @return the synthesized boolean literal
* TODO: move to synthesizer
*/
public BooleanLit createTrue(Position pos) {
return (BooleanLit) xnf.BooleanLit(pos, true).type(xts.Boolean());
}
/**
* Create the boolean litteral "false".
*
* @param pos the Position of the literal in source code
* @return the synthesized boolean literal
* TODO: move to the synthesizer
*/
public BooleanLit createFalse(Position pos) {
return (BooleanLit) xnf.BooleanLit(pos, false).type(xts.Boolean());
}
/**
* Create the boolean negation of a given (boolean) expression.
*
* @param expr the boolean expressin to be negated
* @return a synthesized expression which is the boolean negation of expr
* TODO: move to synthesizer
*/
public Unary createNot(Expr expr) {
return createNot(expr.position(), expr);
}
/**
* Create the boolean negation of a given (boolean) expression.
*
* @param pos the Position of the negated expression in the source code
* @param expr the boolean expression to be negated
* @return a synthesized expression that negates expr
* TODO: move to Synthesizer
*/
public Unary createNot(Position pos, Expr expr) {
assert (expr.type().isBoolean());
return createUnary(pos, Unary.NOT, expr);
}
/**
* Create a unary expression.
*
* @param pos the Position of the unary expression in the source code
* @param op the unary operation of the expression
* @param expr the argument to the unary operator
* @return a synthesized unary expression equivalent to applying op to expr
* TODO: move to Synthesizer
*/
public Unary createUnary(Position pos, polyglot.ast.Unary.Operator op, Expr expr) {
return (Unary) xnf.Unary(pos, op, expr).type(expr.type());
}
/**
* Create a local variable reference copied from another
*
* @param pos the Position of the new local variable reference in source code.
* @param local the local variable reference to copy
* @return a synthesized local variable reference
* TODO: move to Synthesizer
*/
public Local createLocal(Position pos, Local local) {
return syn.createLocal(pos, local.localInstance());
}
/**
* Create a local variable reference.
*
* @param pos the Position of the reference in the source code
* @param decl the declaration of the local variable
* @return the synthesized Local variable reference
* TODO: move into synthesizer, rewrite others
* @deprecated
*/
public Local createLocal(Position pos, LocalDecl decl) {
return createLocal(pos, decl.localDef().asInstance());
}
/**
* Create a local variable reference.
*
* @param pos the Position of the reference in the source code
* @param li a type system object representing this local variable
* @return the synthesized Local variable reference
* TODO: moved into synthesizer, rewrite others
* @deprecated
*/
public Local createLocal(Position pos, LocalInstance li) {
return (Local) xnf.Local(pos, xnf.Id(pos, li.name())).localInstance(li).type(li.type());
}
/**
* Create a binary expression.
*
* @param pos the Position of the expression in the source code
* @param left the first operand
* @param op the operator
* @param right the second operand
* @return the synthesized Binary expression: (left op right)
* TODO: move into Synthesizer
*/
public Binary createBinary(Position pos, Expr left, polyglot.ast.Binary.Operator op, Expr right) {
try {
return (Binary) xnf.Binary(pos, left, op, right).typeCheck(this);
} catch (SemanticException e) {
throw new InternalCompilerError("Attempting to synthesize a Binary that cannot be typed", pos, e);
}
}
/**
* Create an assignment expression.
*
* @param pos the Position of the assignment in the source code
* @param target the lval being assigned to
* @param op the assignment operator
* @param source the right-hand-side of the assignment
* @return the synthesized Assign expression: (target op source)
* TODO: move into Synthesizer
*/
public Assign createAssign(Position pos, Expr target, Operator op, Expr source) {
return (Assign) xnf.Assign(pos, target, op, source).type(target.type());
}
/**
* Create a coercion (implicit conversion) expression.
*
* @param pos the Position of the cast in the source code
* @param expr the Expr being cast
* @param toType the resultant type
* @return the synthesized Cast expression: (expr as toType), or null if the conversion is invalid
* TODO: move into Synthesizer
*/
public X10Cast createCoercion(Position pos, Expr expr, Type toType) {
try {
// FIXME: Have to typeCheck, because the typechecker has already desugared this to a conversion chain
return (X10Cast) xnf.X10Cast( pos,
xnf.CanonicalTypeNode(pos, toType),
expr,
Converter.ConversionType.UNKNOWN_IMPLICIT_CONVERSION ).typeCheck(this);
} catch (SemanticException e) {
// work around for XTENLANG-1335
try {
return (X10Cast) xnf.X10Cast( pos,
xnf.CanonicalTypeNode(pos, toType),
expr,
Converter.ConversionType.UNCHECKED ).typeCheck(this);
} catch (SemanticException x) {
// return null;
}
// end work around for XTENLANG-1335
return null;
}
}
/**
* Create a reference to a field of an object or struct.
* If the receiver has a self constraint, propagate the constraint appropriately.
*
* @param pos the Position of the reference
* @param receiver the object or struct containing the field
* @param name the Name of the field
* @return the synthesized Field expression: (container . name), or null if no such field
* TODO: move into Synthesizer
*/
public Field createFieldRef(Position pos, Expr receiver, Name name) {
final Type type = receiver.type();
X10FieldInstance fi = X10TypeMixin.getProperty(type, name);
if (null == fi) {
fi = (X10FieldInstance) type.toClass().fieldNamed(name);
}
if (null == fi) return null;
return createFieldRef(pos, receiver, fi);
}
/**
* Create a reference to a field of an object or struct.
* If the receiver has a self constraint, propagate the constraint appropriately.
*
* @param pos the Position of the reference in the source code
* @param receiver the object or struct containing the field
* @param fi a type system object representing this field
* @return the synthesized Field expression
* TODO: move into Synthesizer
*/
public Field createFieldRef(Position pos, Expr receiver, X10FieldInstance fi) {
Field f = xnf.Field(pos, receiver, xnf.Id(pos, fi.name())).fieldInstance(fi);
Type type = fi.rightType();
// propagate self binding (if any)
CConstraint c = X10TypeMixin.realX(receiver.type());
XTerm term = X10TypeMixin.selfVarBinding(c); // the RHS of {self==x} in c
if (term != null) {
type = addSelfConstraint(type, xts.xtypeTranslator().trans(c, term, fi));
assert (null != type);
}
return (Field) f.type(type);
}
/**
* Create a Call to a static method.
*
* @param pos the Position of the call in the source code
* @param container the class that defines the static method
* @param name the name of the static method
* @param args the arguments to the static method
* @return the synthesized Call to the method of the given type with the required name taking the prescribed arguments,
* or null if no such method
* TODO: move to Synthesizer
*/
public X10Call createStaticCall(Position pos, Type container, Name name, Expr... args) {
X10MethodInstance mi = createMethodInstance(container, name, args);
if (null == mi) return null;
return createStaticCall(pos, mi, args);
}
/**
* Create a Call to a generic static method.
*
* @param pos the Position of the call in the source code
* @param container the class of the generic static method
* @param name the name of the generic static method
* @param typeArgs the type arguments to the generic static method
* @param args the arguments to the generic static method
* @return the synthesized Call to the method of the given type
* with the required name taking the prescribed type arguments and arguments,
* or null if no such method
* TODO: move to Synthesizer
*/
public X10Call createStaticCall(Position pos, Type container, Name name, List<Type> typeArgs, Expr... args) {
X10MethodInstance mi = createMethodInstance(container, name, typeArgs, args);
if (null == mi) return null;
return createStaticCall(pos, mi, args);
}
/**
* Create a Call to a static method.
* The name and type of method (and any generic type arguments) are contained in the method instance.
*
* @param pos the Position of the call in the source code
* @param mi a type system object representing the static method being called
* @param args the arguments to the call to the static method
* @return the synthesized Call to the specified method taking the prescribed arguments
* TODO: move to Synthesizer
*/
public X10Call createStaticCall(Position pos, X10MethodInstance mi, Expr... args) {
List<Type> typeParams = mi.typeParameters();
List<TypeNode> typeParamNodes = new ArrayList<TypeNode>();
for (Type t : typeParams) {
typeParamNodes.add(xnf.CanonicalTypeNode(pos, t));
}
return (X10Call) xnf.X10Call( pos,
xnf.CanonicalTypeNode(pos, mi.container()),
xnf.Id(pos, mi.name()),
typeParamNodes,
Arrays.asList(args) ).methodInstance(mi).type(mi.returnType());
}
/**
* Create a Call to an instance method.
*
* @param pos the Position of the call in the source code
* @param receiver the object on which the instance method is being called
* @param name the Name of the instance method
* @param args the arguments to the instance method
* @return the synthesized Call to a method on the specified receiver with the required name and prescribed arguments,
* or null if no such method
* TODO: move to Synthesizer
*/
public X10Call createInstanceCall(Position pos, Expr receiver, Name name, Expr... args) {
X10MethodInstance mi = createMethodInstance(receiver, name, args);
if (null == mi) return null;
return createInstanceCall(pos, receiver, mi, args);
}
/**
* Create a Call to a generic instance method.
*
* @param pos the Position of the call in the source code
* @param receiver the object on which the generic instance method is being called
* @param name the Name of the generic instance method
* @param typeArgs the type arguments to the generic instance method
* @param args the arguments to the generic instance method
* @return the synthesized Call to the method on the specified receiver
* with the required name taking the prescribed type arguments and arguments,
* or null if no such method
* TODO: move to Synthesizer
*/
public X10Call createInstanceCall(Position pos, Expr receiver, Name name, List<Type> typeArgs, Expr... args) {
X10MethodInstance mi = createMethodInstance(receiver, name, typeArgs, args);
if (null == mi) return null;
return createInstanceCall(pos, receiver, mi, args);
}
/**
* Create a Call to an instance method.
* The Name and any type arguments to the instance method are encoded in the method instance.
*
* @param pos the Position of the call in the source code
* @param receiver the object on which the instance method is being called
* @param mi a type system object representing the instance method being called
* @param args the arguments to the instance method
* @return the synthesized Call to the specified method on the given receiver taking the prescribed arguments,
* or null if no such method
* TODO: move to Synthesizer
*/
public X10Call createInstanceCall(Position pos, Expr receiver, X10MethodInstance mi, Expr... args) {
List<Type> typeParams = mi.typeParameters();
List<TypeNode> typeParamNodes = new ArrayList<TypeNode>();
for (Type t : typeParams) {
typeParamNodes.add(xnf.CanonicalTypeNode(pos, t));
}
return (X10Call) xnf.X10Call( pos,
receiver,
xnf.Id(pos, mi.name()),
typeParamNodes,
Arrays.asList(args) ).methodInstance(mi).type(mi.returnType());
}
// helper methods that return type system instances
/**
* Create a type system object representing a specified Generic method (either static or instance).
*
* @param container the type (static method) or receiver (instance method) of the method call
* @param name the Name of the method to be called
* @param typeArgs the type arguments to the method
* @param args the arguments to the method
* @return the synthesized method instance for this method call
* @throws InternalCompilerError if the required method instance cannot be created
* TODO: move to a type system helper class
*/
public X10MethodInstance createMethodInstance(Type container, Name name, List<Type> typeArgs, Expr... args) {
List<Type> argTypes = getExprTypes(args);
return createMethodInstance(container, name, typeArgs, argTypes);
}
/**
* @param container
* @param name
* @param typeArgs
* @param argTypes
* @return
*/
public X10MethodInstance createMethodInstance(Type container, Name name, List<Type> typeArgs, List<Type> argTypes) {
Context context = context();
return createMethodInstance(container, name, typeArgs, argTypes, context);
}
/**
return createMethodInstance(container, name, typeArgs, argTypes, context);
* @param container
* @param name
* @param typeArgs
* @param argTypes
* @param context
* @return
*/
public X10MethodInstance createMethodInstance(Type container, Name name, List<Type> typeArgs, List<Type> argTypes, Context context) {
try {
return xts.findMethod(container, xts.MethodMatcher(container, name, typeArgs, argTypes, context));
} catch (SemanticException e) {
throw new InternalCompilerError("Unable to find required method instance", container.position(), e);
}
}
/**
* Create a type system object representing a specified method (either static or instance).
*
* @param container the type (static method) or receiver (instance method) of the method call
* @param name the Name of the method to be called
* @param args the arguments to the method
* @return the synthesized method instance for this method call
* throws InternalCompilerError if the required method instance cannot be created
* TODO: move to a type system helper class
*/
public X10MethodInstance createMethodInstance(Type container, Name name, Expr... args) {
List<Type> argTypes = getExprTypes(args);
try {
return xts.findMethod(container, xts.MethodMatcher(container, name, argTypes, context()) );
} catch (SemanticException e) {
throw new InternalCompilerError("Unable to find required method instance", container.position(), e);
}
}
/**
* Create a type system object representing a specified Generic instance method.
*
* @param receiver the receiver of the (instance) method call
* @param name the Name of the method to be called
* @param typeArgs the type arguments to the method
* @param args the arguments to the method
* @return the synthesized method instance for this method call
* @throws InternalCompilerError if the required method instance cannot be created
* TODO: move to a type system helper class
*/
public X10MethodInstance createMethodInstance(Expr receiver, Name name, List<Type> typeArgs, Expr... args) {
return createMethodInstance(receiver.type(), name, typeArgs, args);
}
/**
* Create a type system object representing a specified instance method.
*
* @param receiver the receiver of the (instance) method call
* @param name the Name of the method to be called
* @param args the arguments to the method
* @return the synthesized method instance for this method call
* throws InternalCompilerError if the required method instance cannot be created
* TODO: move to a type system helper class
*/
public X10MethodInstance createMethodInstance(Expr receiver, Name name, Expr... args) {
return createMethodInstance(receiver.type(), name, args);
}
/**
* Create a new Name for a temporary variable.
*
* @return the newly created name
* TODO: move to Synthesizer
*/
public Name createTemporaryName() {
return Name.makeFresh("t");
}
/**
* Find the Types for a sequence of expressions.
*
* @param args the sequence of expressions to be typed
* @return a List of the Types of the args
*/
private static List<Type> getExprTypes(Expr... args) {
List<Type> argTypes = new ArrayList<Type> (args.length);
for (Expr a : args) {
argTypes.add(a.type());
}
return argTypes;
}
}
| false | true | public Node visitForLoop(ForLoop_c loop) {
Position pos = loop.position();
X10Formal formal = (X10Formal) loop.formal();
Expr domain = loop.domain();
Stmt body = loop.body();
if (VERBOSE) {
System.out.println("\nOptimizing ForLoop at " +pos);
loop.prettyPrint(System.out);
System.out.println();
}
// if domain <: DistArray, transform to Distribution
if (xts.isX10DistArray(domain.type())) {
if (VERBOSE) System.out.println(" domain is DistArray, tranforming to Dist");
domain = createFieldRef(pos, domain, DIST);
assert (null != domain);
}
// if domain <: Distribution, transform to Region
if (((X10TypeSystem_c) xts).isDistribution(domain.type())) {
if (VERBOSE) System.out.println(" domain is Dist, transforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
// if domain <: Array, transform to Region
if (xts.isX10Array(domain.type())) {
if (VERBOSE) System.out.println(" domain is Array, tranforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
Id label = createLabel(pos);
Context context = (Context) context();
List<Formal> formalVars = formal.vars();
boolean named = !formal.isUnnamed();
boolean isRect = X10TypeMixin.isRect(domain.type(), context);
Integer domainRank = (Integer) getPropertyConstantValue(domain, RANK);
int rank = (null != domainRank) ? (int) domainRank :
(null != formalVars) ? formalVars.size() :
-1;
assert null == formalVars || formalVars.isEmpty() || formalVars.size() == rank;
// SPECIAL CASE (XTENLANG-1340):
// for (p(i) in e1..e2) S =>
// val min=e1; val max=e2; for(var z:Int=min; z<=max; z++){ val p=Point.make(z); val i=z; S }
// TODO inline (min and max), scalar replace Region object and its constituent Arrays then delete this code
//
if (1 == rank && domain instanceof RegionMaker) {
List<Expr> args = ((RegionMaker) loop.domain()).arguments();
assert (args.size() == 2);
Expr low = args.get(0);
Expr high = args.get(1);
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh("i")
: Name.makeFresh(formalVars.get(0).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, low);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, high);
LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, createLocal(pos, minLDecl));
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (named) {
// declare the formal variable as a local and initialize it
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, varLDecl));
LocalDecl formalLDecl = transformFormalToLocalDecl(formal, formExpr);
bodyStmts.add(formalLDecl);
}
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(0), createLocal(pos, varLDecl)));
}
bodyStmts.add(body);
body = createBlock(loop.body().position(), bodyStmts);
For forLoop = createStandardFor(pos, varLDecl, cond, update, body);
return createBlock(pos, minLDecl, maxLDecl, forLoop);
}
// transform rectangular regions of known rank
if (xts.isRegion(domain.type()) && isRect && rank > 0) {
assert xts.isPoint(formal.declType());
if (VERBOSE) System.out.println(" rectangular region, rank=" +rank+ " point=" +formal);
if (1 < rank) {
body = labelFreeBreaks(body, label);
}
List<Stmt> stmts = new ArrayList<Stmt>();
Name prefix = named ? formal.name().id() : Name.make("p");
// cache the value of domain in a local temporary variable
LocalDecl domLDecl = createLocalDecl(domain.position(), Flags.FINAL, Name.makeFresh(prefix), domain);
stmts.add(domLDecl);
// Prepare to redeclare the formal iterate as local Point variable (if the formal is not anonymous)
Type indexType = null; // type of the formal var initializer (if any)
LocalDecl indexLDecl = null; // redeclaration of the formal var (if it has a name)
if (named) {
// create a rail to contain the value of the formal at each iteration
Name indexName = Name.makeFresh(prefix);
indexType = xts.Rail(xts.Int()); // PlaceChecker.AddIsHereClause(xts.Rail(xts.Int()), context);
List<Type> railType = Collections.<Type>singletonList(xts.Int());
Expr indexInit = createStaticCall(pos, xts.Rail(), MAKE, railType, createIntLit(rank));
indexLDecl = createLocalDecl(pos, Flags.FINAL, indexName, indexType, indexInit);
// add the declaration of the index rail to the list of statements to be executed before the loop nest
stmts.add(indexLDecl);
}
LocalDecl varLDecls[] = new LocalDecl[rank];
// create the loop nest (from the inside out)
for (int r=rank-1; 0<=r; r--) {
// create new names for the r-th iterate and limits
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh(prefix)
: Name.makeFresh(formalVars.get(r).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
// create an AST node for the calls to domain.min() and domain.max()
Expr minVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MIN, createIntLit(r));
Expr maxVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MAX, createIntLit(r));
// create an AST node for the declaration of the temporary locations for the r-th var, min, and max
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, minVal);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, maxVal);
LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, createLocal(pos, minLDecl));
varLDecls[r] = varLDecl;
// add the declarations for the r-th min and max to the list of statements to be executed before the loop nest
stmts.add(minLDecl);
stmts.add(maxLDecl);
// create expressions for the second and third positions in the r-th for clause
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(r), createLocal(pos, varLDecl)));
}
// concoct declaration for formal, in case it might be referenced in the body
if (named) {
// set the r-th slot int the index rail to the current value of the r-th iterate
Expr setExpr = createInstanceCall( pos,
createLocal(pos, indexLDecl),
SET,
createLocal(pos, varLDecl),
createIntLit(r) );
bodyStmts.addAll(convertToStmtList(setExpr));
if (r+1 == rank) { // the innermost loop
// declare the formal variable as a local and initialize it to the index rail
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, indexLDecl));
bodyStmts.add(transformFormalToLocalDecl(formal, formExpr));
}
}
bodyStmts.add(body);
body = createBlock(pos, bodyStmts);
// create the AST node for the r-th concocted for-statement
body = createStandardFor(pos, varLDecl, cond, update, body);
}
if (1 < rank) {
body = xnf.Labeled(body.position(), label, body);
}
body = explodePoint(formal, indexLDecl, varLDecls, body);
stmts.add(body);
Block result = createBlock(pos, stmts);
if (VERBOSE) result.dump(System.out);
return result;
}
assert (xts.isSubtype(domain.type(), xts.Iterable(xts.Any()), context));
Name iterName = named ? Name.makeFresh(formal.name().id()) : Name.makeFresh();
Expr iterInit = createInstanceCall(pos, domain, ITERATOR);
LocalDecl iterLDecl = createLocalDecl(pos, Flags.FINAL, iterName, iterInit);
Expr hasExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), HASNEXT);
Expr nextExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), NEXT);
if (!xts.typeEquals(nextExpr.type(), formal.declType(), context)) {
Expr newNextExpr = createCoercion(pos, nextExpr, formal.declType());
if (null == newNextExpr)
throw new InternalCompilerError("Unable to cast "+nextExpr+" to the iterated type "+formal.declType(), pos);
nextExpr = newNextExpr;
}
List<Stmt> bodyStmts = new ArrayList<Stmt>();
LocalDecl varLDecl = transformFormalToLocalDecl(formal, nextExpr);
bodyStmts.add(varLDecl);
if (null != formalVars && !formalVars.isEmpty()) try {
bodyStmts.addAll(formal.explode(this));
} catch (SemanticException e) {
throw new InternalCompilerError("We cannot explode the formal. Huh?", formal.position(), e);
}
if (body instanceof Block) {
bodyStmts.addAll(((Block) body).statements());
} else {
bodyStmts.add(body);
}
Stmt result = createStandardFor(pos, iterLDecl, hasExpr, createBlock(pos, bodyStmts));
if (VERBOSE) result.dump(System.out);
return result;
}
| public Node visitForLoop(ForLoop_c loop) {
Position pos = loop.position();
X10Formal formal = (X10Formal) loop.formal();
Expr domain = loop.domain();
Stmt body = loop.body();
if (VERBOSE) {
System.out.println("\nOptimizing ForLoop at " +pos);
loop.prettyPrint(System.out);
System.out.println();
}
// if domain <: DistArray, transform to Distribution
if (xts.isX10DistArray(domain.type())) {
if (VERBOSE) System.out.println(" domain is DistArray, tranforming to Dist");
domain = createFieldRef(pos, domain, DIST);
assert (null != domain);
}
// if domain <: Distribution, transform to Region
if (((X10TypeSystem_c) xts).isDistribution(domain.type())) {
if (VERBOSE) System.out.println(" domain is Dist, transforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
// if domain <: Array, transform to Region
if (xts.isX10Array(domain.type())) {
if (VERBOSE) System.out.println(" domain is Array, tranforming to Region");
domain = createFieldRef(pos, domain, REGION);
assert (null != domain);
}
Id label = createLabel(pos);
Context context = (Context) context();
List<Formal> formalVars = formal.vars();
boolean named = !formal.isUnnamed();
boolean isRect = X10TypeMixin.isRect(domain.type(), context);
Integer domainRank = (Integer) getPropertyConstantValue(domain, RANK);
int rank = (null != domainRank) ? (int) domainRank :
(null != formalVars) ? formalVars.size() :
-1;
assert null == formalVars || formalVars.isEmpty() || formalVars.size() == rank;
// SPECIAL CASE (XTENLANG-1340):
// for (p(i) in e1..e2) S =>
// val min=e1; val max=e2; for(var z:Int=min; z<=max; z++){ val p=Point.make(z); val i=z; S }
// TODO inline (min and max), scalar replace Region object and its constituent Arrays then delete this code
//
if (1 == rank && domain instanceof RegionMaker) {
List<Expr> args = ((RegionMaker) loop.domain()).arguments();
assert (args.size() == 2);
Expr low = args.get(0);
Expr high = args.get(1);
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh("i")
: Name.makeFresh(formalVars.get(0).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, low);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, high);
LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, xts.Int(), createLocal(pos, minLDecl));
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (named) {
// declare the formal variable as a local and initialize it
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, varLDecl));
LocalDecl formalLDecl = transformFormalToLocalDecl(formal, formExpr);
bodyStmts.add(formalLDecl);
}
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(0), createLocal(pos, varLDecl)));
}
bodyStmts.add(body);
body = createBlock(loop.body().position(), bodyStmts);
For forLoop = createStandardFor(pos, varLDecl, cond, update, body);
return createBlock(pos, minLDecl, maxLDecl, forLoop);
}
// transform rectangular regions of known rank
if (xts.isRegion(domain.type()) && isRect && rank > 0) {
assert xts.isPoint(formal.declType());
if (VERBOSE) System.out.println(" rectangular region, rank=" +rank+ " point=" +formal);
if (1 < rank) {
body = labelFreeBreaks(body, label);
}
List<Stmt> stmts = new ArrayList<Stmt>();
Name prefix = named ? formal.name().id() : Name.make("p");
// cache the value of domain in a local temporary variable
LocalDecl domLDecl = createLocalDecl(domain.position(), Flags.FINAL, Name.makeFresh(prefix), domain);
stmts.add(domLDecl);
// Prepare to redeclare the formal iterate as local Point variable (if the formal is not anonymous)
Type indexType = null; // type of the formal var initializer (if any)
LocalDecl indexLDecl = null; // redeclaration of the formal var (if it has a name)
if (named) {
// create a rail to contain the value of the formal at each iteration
Name indexName = Name.makeFresh(prefix);
indexType = xts.Rail(xts.Int()); // PlaceChecker.AddIsHereClause(xts.Rail(xts.Int()), context);
List<Type> railType = Collections.<Type>singletonList(xts.Int());
Expr indexInit = createStaticCall(pos, xts.Rail(), MAKE, railType, createIntLit(rank));
indexLDecl = createLocalDecl(pos, Flags.FINAL, indexName, indexType, indexInit);
// add the declaration of the index rail to the list of statements to be executed before the loop nest
stmts.add(indexLDecl);
}
LocalDecl varLDecls[] = new LocalDecl[rank];
// create the loop nest (from the inside out)
for (int r=rank-1; 0<=r; r--) {
// create new names for the r-th iterate and limits
Name varName = null == formalVars || formalVars.isEmpty() ? Name.makeFresh(prefix)
: Name.makeFresh(formalVars.get(r).name().id());
Name minName = Name.makeFresh(varName+ "min");
Name maxName = Name.makeFresh(varName+ "max");
// create an AST node for the calls to domain.min() and domain.max()
Expr minVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MIN, createIntLit(r));
Expr maxVal = createInstanceCall(pos, createLocal(domain.position(), domLDecl), MAX, createIntLit(r));
// create an AST node for the declaration of the temporary locations for the r-th var, min, and max
LocalDecl minLDecl = createLocalDecl(pos, Flags.FINAL, minName, minVal);
LocalDecl maxLDecl = createLocalDecl(pos, Flags.FINAL, maxName, maxVal);
LocalDecl varLDecl = createLocalDecl(pos, Flags.NONE, varName, xts.Int(), createLocal(pos, minLDecl));
varLDecls[r] = varLDecl;
// add the declarations for the r-th min and max to the list of statements to be executed before the loop nest
stmts.add(minLDecl);
stmts.add(maxLDecl);
// create expressions for the second and third positions in the r-th for clause
Expr cond = createBinary(domain.position(), createLocal(pos, varLDecl), Binary.LE, createLocal(pos, maxLDecl));
Expr update = createAssign(domain.position(), createLocal(pos, varLDecl), Assign.ADD_ASSIGN, createIntLit(1));
List<Stmt> bodyStmts = new ArrayList<Stmt>();
if (null != formalVars && !formalVars.isEmpty()) {
bodyStmts.add(transformFormalToLocalDecl((X10Formal) formalVars.get(r), createLocal(pos, varLDecl)));
}
// concoct declaration for formal, in case it might be referenced in the body
if (named) {
// set the r-th slot int the index rail to the current value of the r-th iterate
Expr setExpr = createInstanceCall( pos,
createLocal(pos, indexLDecl),
SET,
createLocal(pos, varLDecl),
createIntLit(r) );
bodyStmts.addAll(convertToStmtList(setExpr));
if (r+1 == rank) { // the innermost loop
// declare the formal variable as a local and initialize it to the index rail
Expr formExpr = createStaticCall(pos, formal.declType(), MAKE, createLocal(pos, indexLDecl));
bodyStmts.add(transformFormalToLocalDecl(formal, formExpr));
}
}
bodyStmts.add(body);
body = createBlock(pos, bodyStmts);
// create the AST node for the r-th concocted for-statement
body = createStandardFor(pos, varLDecl, cond, update, body);
}
if (1 < rank) {
body = xnf.Labeled(body.position(), label, body);
}
body = explodePoint(formal, indexLDecl, varLDecls, body);
stmts.add(body);
Block result = createBlock(pos, stmts);
if (VERBOSE) result.dump(System.out);
return result;
}
assert (xts.isSubtype(domain.type(), xts.Iterable(xts.Any()), context));
Name iterName = named ? Name.makeFresh(formal.name().id()) : Name.makeFresh();
Expr iterInit = createInstanceCall(pos, domain, ITERATOR);
LocalDecl iterLDecl = createLocalDecl(pos, Flags.FINAL, iterName, iterInit);
Expr hasExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), HASNEXT);
Expr nextExpr = createInstanceCall(pos, createLocal(pos, iterLDecl), NEXT);
if (!xts.typeEquals(nextExpr.type(), formal.declType(), context)) {
Expr newNextExpr = createCoercion(pos, nextExpr, formal.declType());
if (null == newNextExpr)
throw new InternalCompilerError("Unable to cast "+nextExpr+" to the iterated type "+formal.declType(), pos);
nextExpr = newNextExpr;
}
List<Stmt> bodyStmts = new ArrayList<Stmt>();
LocalDecl varLDecl = transformFormalToLocalDecl(formal, nextExpr);
bodyStmts.add(varLDecl);
if (null != formalVars && !formalVars.isEmpty()) try {
bodyStmts.addAll(formal.explode(this));
} catch (SemanticException e) {
throw new InternalCompilerError("We cannot explode the formal. Huh?", formal.position(), e);
}
if (body instanceof Block) {
bodyStmts.addAll(((Block) body).statements());
} else {
bodyStmts.add(body);
}
Stmt result = createStandardFor(pos, iterLDecl, hasExpr, createBlock(pos, bodyStmts));
if (VERBOSE) result.dump(System.out);
return result;
}
|
diff --git a/lib-core/src/main/java/com/silverpeas/form/AbstractForm.java b/lib-core/src/main/java/com/silverpeas/form/AbstractForm.java
index da199069b2..33425e05d7 100644
--- a/lib-core/src/main/java/com/silverpeas/form/AbstractForm.java
+++ b/lib-core/src/main/java/com/silverpeas/form/AbstractForm.java
@@ -1,395 +1,395 @@
/**
* Copyright (C) 2000 - 2009 Silverpeas
*
* 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.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* 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.silverpeas.form;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspWriter;
import org.apache.commons.fileupload.FileItem;
import com.silverpeas.util.StringUtil;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import java.util.Arrays;
/**
* This abstract class implements the form interface and provides for all concretes classes a
* default implementation of some displaying methods.
*/
public abstract class AbstractForm implements Form {
private List<FieldTemplate> fieldTemplates;
private String title = "";
public static final String CONTEXT_FORM_FILE = "Images";
public static final String CONTEXT_FORM_IMAGE = "XMLFormImages";
/**
* Creates a new form from the specified template of records.
* @param template the record template.
* @throws FormException if an error occurs while setting up the form.
*/
public AbstractForm(final RecordTemplate template) throws FormException {
if (template != null) {
fieldTemplates = Arrays.asList(template.getFieldTemplates());
} else {
fieldTemplates = new ArrayList<FieldTemplate>();
}
}
/**
* Gets the template of all of the fields that made this form.
* @return
*/
public List<FieldTemplate> getFieldTemplates() {
return fieldTemplates;
}
/**
* Gets the title of this form.
* @return the title of this form or an empty string if it isn't set.
*/
@Override
public String getTitle() {
return (title == null ? "": title);
}
/**
* Sets the form title.
* @param title the new title of the form.
*/
public void setTitle(final String title) {
this.title = title;
}
/**
* Prints the javascripts which will be used to control the new values given to the data record
* fields. The error messages may be adapted to a local language. The RecordTemplate gives the
* field type and constraints. The RecordTemplate gives the local label too. Never throws an
* Exception but log a silvertrace and writes an empty string when :
* <UL>
* <LI>a field is unknown by the template.
* <LI>a field has not the required type.
* </UL>
* @param jw the JSP writer into which the javascript is written.
* @param pagesContext the JSP page context.
*/
@Override
public void displayScripts(final JspWriter jw, final PagesContext pagesContext) {
try {
String language = pagesContext.getLanguage();
PagesContext pc = null;
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw, true);
//Iterator<FieldTemplate> itFields = null;
if (!fieldTemplates.isEmpty()) {
FieldTemplate fieldTemplate = fieldTemplates.get(0);
- out.append("<script type=\"text/javascript\" src=\"/weblib/xmlforms/")
+ out.append("<script type=\"text/javascript\" src=\"/weblib/xmlForms/")
.append(fieldTemplate.getTemplateName())
.append(".js\"></script>\n");
pc = new PagesContext(pagesContext);
pc.incCurrentFieldIndex(1);
}
out.append(Util.getJavascriptIncludes())
.append("\n<script type=\"text/javascript\">\n")
.append(" var errorNb = 0;\n")
.append(" var errorMsg = \"\";\n")
.append("function addXMLError(message) {\n")
.append(" errorMsg+=\" - \"+message+\"\\n\";\n")
.append(" errorNb++;\n")
.append("}\n")
.append("function getXMLField(fieldName) {\n")
.append(" return document.getElementById(fieldName);\n")
.append("}\n")
.append("function isCorrectForm() {\n")
.append(" errorMsg = \"\";\n")
.append(" errorNb = 0;\n")
.append(" var field;\n")
.append(" \n\n");
for (FieldTemplate fieldTemplate : fieldTemplates) {
if (fieldTemplate != null) {
String fieldDisplayerName = fieldTemplate.getDisplayerName();
String fieldType = fieldTemplate.getTypeName();
FieldDisplayer fieldDisplayer = null;
try {
if (fieldDisplayerName == null || fieldDisplayerName.isEmpty()) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
out.append(" field = document.getElementById(\"")
.append(fieldTemplate.getFieldName())
.append("\");\n")
.append(" if (field != null) {\n");
fieldDisplayer.displayScripts(out, fieldTemplate, pc);
out.println("}\n");
pc.incCurrentFieldIndex(fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate,
pc));
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_UNKNOWN_FIELD", null, fe);
}
}
}
out.append(" \n\n")
.append(" switch(errorNb)\n")
.append(" {\n")
.append(" case 0 :\n")
.append(" result = true;\n")
.append(" break;\n")
.append(" case 1 :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append(" 1 ")
.append(Util.getString("GML.error", language))
.append(" : \\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" default :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append("\" + errorNb + \" ")
.append(Util.getString("GML.errors", language))
.append(" :\\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" }\n")
.append(" return result;\n")
.append("}\n")
.append(" \n\n")
.append("</script>\n");
out.flush();
jw.write(sw.toString());
} catch (java.io.IOException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_CANT_WRITE", null, fe);
}
}
/**
* Prints this form into the specified JSP writer according to the specified records of data that
* populate the form fields.
* @param out the JSP writer.
* @param pagesContext the JSP page context.
* @param record the record the data records embbed the form fields.
*/
@Override
public abstract void display(JspWriter out, PagesContext pagesContext, DataRecord record);
/**
* Updates the values of the dataRecord using the RecordTemplate to extra control information
* (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from
* the request.
* @param items the item of a form in which is embbeded multipart data.
* @param record the record of data.
* @param pagesContext the page context.
* @throw FormException if the field type is not a managed type.
* @throw FormException if the field doesn't accept the new value.
*/
@Override
public List<String> update(List<FileItem> items, DataRecord record, PagesContext pagesContext) {
return update(items, record, pagesContext, true);
}
/**
* Updates the values of the dataRecord using the RecordTemplate to extra control information
* (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from
* the request.
* @param items the item of a form in which is embbeded multipart data.
* @param record the record of data.
* @param pagesContext the page context.
* @param updateWysiwyg flag indicating if all of WYSIWYG data can be updated.
* @throw FormException if the field type is not a managed type.
* @throw FormException if the field doesn't accept the new value.
*/
@Override
public List<String> update(List<FileItem> items, DataRecord record, PagesContext pagesContext,
boolean updateWysiwyg) {
List<String> attachmentIds = new ArrayList<String>();
for (FieldTemplate fieldTemplate : fieldTemplates) {
FieldDisplayer fieldDisplayer = null;
if (fieldTemplate != null) {
String fieldName = fieldTemplate.getFieldName();
String fieldType = fieldTemplate.getTypeName();
String fieldDisplayerName = fieldTemplate.getDisplayerName();
try {
if ((fieldDisplayerName == null) || (fieldDisplayerName.isEmpty())) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
if ((!"wysiwyg".equals(fieldDisplayerName) || updateWysiwyg)) {
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
attachmentIds.addAll(fieldDisplayer.update(items, record.getField(fieldName),
fieldTemplate, pagesContext));
}
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.update", "form.EXP_UNKNOWN_FIELD", null, fe);
} catch (Exception e) {
SilverTrace.error("form", "AbstractForm.update", "form.EXP_UNKNOWN_FIELD", null, e);
}
}
}
return attachmentIds;
}
/**
* Updates the values of the dataRecord using the RecordTemplate to extra control information
* (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from
* the request.
* @param items the item of a form in which is embbeded multipart data.
* @param record the record of data.
* @param pagesContext the page context.
* @throw FormException if the field type is not a managed type.
* @throw FormException if the field doesn't accept the new value.
*/
@Override
public List<String> updateWysiwyg(List<FileItem> items, DataRecord record,
PagesContext pagesContext) {
List<String> attachmentIds = new ArrayList<String>();
for (FieldTemplate fieldTemplate : fieldTemplates) {
FieldDisplayer fieldDisplayer = null;
if (fieldTemplate != null) {
String fieldName = fieldTemplate.getFieldName();
String fieldType = fieldTemplate.getTypeName();
String fieldDisplayerName = fieldTemplate.getDisplayerName();
try {
if ((fieldDisplayerName == null) || (fieldDisplayerName.isEmpty())) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
if ("wysiwyg".equals(fieldDisplayerName)) {
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
attachmentIds.addAll(fieldDisplayer.update(items, record.getField(fieldName),
fieldTemplate, pagesContext));
}
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.update", "form.EXP_UNKNOWN_FIELD", null, fe);
} catch (Exception e) {
SilverTrace.error("form", "AbstractForm.update", "form.EXP_UNKNOWN_FIELD", null, e);
}
}
}
return attachmentIds;
}
/**
* Is the form is empty?
* A form is empty if all of its fields aren't valued (no data associated with them).
* @param items the items embbeding multipart data in the form.
* @param record the record of data.
* @param pagesContext the page context.
* @return true if one of the form field has no data.
*/
@Override
public boolean isEmpty(List<FileItem> items, DataRecord record, PagesContext pagesContext) {
boolean isEmpty = true;
for (FieldTemplate fieldTemplate : fieldTemplates) {
FieldDisplayer fieldDisplayer = null;
if (fieldTemplate != null) {
String fieldType = fieldTemplate.getTypeName();
String fieldDisplayerName = fieldTemplate.getDisplayerName();
try {
if (!StringUtil.isDefined(fieldDisplayerName)) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
String itemName = fieldTemplate.getFieldName();
FileItem item = getParameter(items, itemName);
if (item != null && !item.isFormField() && StringUtil.isDefined(item.getName())) {
isEmpty = false;
} else {
String itemValue = getParameterValue(items, itemName, pagesContext.getEncoding());
isEmpty = !StringUtil.isDefined(itemValue);
}
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.isEmpty", "form.EXP_UNKNOWN_FIELD", null, fe);
} catch (Exception e) {
SilverTrace.error("form", "AbstractForm.isEmpty", "form.EXP_UNKNOWN_FIELD", null, e);
}
}
if (! isEmpty) {
break;
}
}
return isEmpty;
}
/**
* Gets the value of the specified parameter from the specified items.
* @param items the items of the form embbeding multipart data.
* @param parameterName the name of the parameter.
* @param encoding the encoding at which the value must be in.
* @return the value of the specified parameter in the given encoding. or null if no such parameter
* is defined in this form.
* @throws UnsupportedEncodingException if the encoding at which the value should be in
* isn't supported.
*/
private String getParameterValue(List<FileItem> items, String parameterName, String encoding)
throws UnsupportedEncodingException {
SilverTrace.debug("form", "AbstractForm.getParameterValue", "root.MSG_GEN_ENTER_METHOD",
"parameterName = " + parameterName);
FileItem item = getParameter(items, parameterName);
if (item != null && item.isFormField()) {
SilverTrace.debug("form", "AbstractForm.getParameterValue", "root.MSG_GEN_EXIT_METHOD",
"parameterValue = " + item.getString());
return item.getString(encoding);
}
return null;
}
/**
* Gets the multipart data of the specified parameter.
* @param items the items of the form with all of the multipart data.
* @param parameterName the name of the parameter.
* @return the item corresponding to the specified parameter.
*/
private FileItem getParameter(final List<FileItem> items, final String parameterName) {
FileItem fileItem = null;
for (FileItem item : items) {
if (parameterName.equals(item.getFieldName())) {
fileItem = item;
break;
}
}
return fileItem;
}
private TypeManager getTypeManager() {
return TypeManager.getInstance();
}
}
| true | true | public void displayScripts(final JspWriter jw, final PagesContext pagesContext) {
try {
String language = pagesContext.getLanguage();
PagesContext pc = null;
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw, true);
//Iterator<FieldTemplate> itFields = null;
if (!fieldTemplates.isEmpty()) {
FieldTemplate fieldTemplate = fieldTemplates.get(0);
out.append("<script type=\"text/javascript\" src=\"/weblib/xmlforms/")
.append(fieldTemplate.getTemplateName())
.append(".js\"></script>\n");
pc = new PagesContext(pagesContext);
pc.incCurrentFieldIndex(1);
}
out.append(Util.getJavascriptIncludes())
.append("\n<script type=\"text/javascript\">\n")
.append(" var errorNb = 0;\n")
.append(" var errorMsg = \"\";\n")
.append("function addXMLError(message) {\n")
.append(" errorMsg+=\" - \"+message+\"\\n\";\n")
.append(" errorNb++;\n")
.append("}\n")
.append("function getXMLField(fieldName) {\n")
.append(" return document.getElementById(fieldName);\n")
.append("}\n")
.append("function isCorrectForm() {\n")
.append(" errorMsg = \"\";\n")
.append(" errorNb = 0;\n")
.append(" var field;\n")
.append(" \n\n");
for (FieldTemplate fieldTemplate : fieldTemplates) {
if (fieldTemplate != null) {
String fieldDisplayerName = fieldTemplate.getDisplayerName();
String fieldType = fieldTemplate.getTypeName();
FieldDisplayer fieldDisplayer = null;
try {
if (fieldDisplayerName == null || fieldDisplayerName.isEmpty()) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
out.append(" field = document.getElementById(\"")
.append(fieldTemplate.getFieldName())
.append("\");\n")
.append(" if (field != null) {\n");
fieldDisplayer.displayScripts(out, fieldTemplate, pc);
out.println("}\n");
pc.incCurrentFieldIndex(fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate,
pc));
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_UNKNOWN_FIELD", null, fe);
}
}
}
out.append(" \n\n")
.append(" switch(errorNb)\n")
.append(" {\n")
.append(" case 0 :\n")
.append(" result = true;\n")
.append(" break;\n")
.append(" case 1 :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append(" 1 ")
.append(Util.getString("GML.error", language))
.append(" : \\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" default :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append("\" + errorNb + \" ")
.append(Util.getString("GML.errors", language))
.append(" :\\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" }\n")
.append(" return result;\n")
.append("}\n")
.append(" \n\n")
.append("</script>\n");
out.flush();
jw.write(sw.toString());
} catch (java.io.IOException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_CANT_WRITE", null, fe);
}
}
| public void displayScripts(final JspWriter jw, final PagesContext pagesContext) {
try {
String language = pagesContext.getLanguage();
PagesContext pc = null;
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw, true);
//Iterator<FieldTemplate> itFields = null;
if (!fieldTemplates.isEmpty()) {
FieldTemplate fieldTemplate = fieldTemplates.get(0);
out.append("<script type=\"text/javascript\" src=\"/weblib/xmlForms/")
.append(fieldTemplate.getTemplateName())
.append(".js\"></script>\n");
pc = new PagesContext(pagesContext);
pc.incCurrentFieldIndex(1);
}
out.append(Util.getJavascriptIncludes())
.append("\n<script type=\"text/javascript\">\n")
.append(" var errorNb = 0;\n")
.append(" var errorMsg = \"\";\n")
.append("function addXMLError(message) {\n")
.append(" errorMsg+=\" - \"+message+\"\\n\";\n")
.append(" errorNb++;\n")
.append("}\n")
.append("function getXMLField(fieldName) {\n")
.append(" return document.getElementById(fieldName);\n")
.append("}\n")
.append("function isCorrectForm() {\n")
.append(" errorMsg = \"\";\n")
.append(" errorNb = 0;\n")
.append(" var field;\n")
.append(" \n\n");
for (FieldTemplate fieldTemplate : fieldTemplates) {
if (fieldTemplate != null) {
String fieldDisplayerName = fieldTemplate.getDisplayerName();
String fieldType = fieldTemplate.getTypeName();
FieldDisplayer fieldDisplayer = null;
try {
if (fieldDisplayerName == null || fieldDisplayerName.isEmpty()) {
fieldDisplayerName = getTypeManager().getDisplayerName(fieldType);
}
fieldDisplayer = getTypeManager().getDisplayer(fieldType, fieldDisplayerName);
if (fieldDisplayer != null) {
out.append(" field = document.getElementById(\"")
.append(fieldTemplate.getFieldName())
.append("\");\n")
.append(" if (field != null) {\n");
fieldDisplayer.displayScripts(out, fieldTemplate, pc);
out.println("}\n");
pc.incCurrentFieldIndex(fieldDisplayer.getNbHtmlObjectsDisplayed(fieldTemplate,
pc));
}
} catch (FormException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_UNKNOWN_FIELD", null, fe);
}
}
}
out.append(" \n\n")
.append(" switch(errorNb)\n")
.append(" {\n")
.append(" case 0 :\n")
.append(" result = true;\n")
.append(" break;\n")
.append(" case 1 :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append(" 1 ")
.append(Util.getString("GML.error", language))
.append(" : \\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" default :\n")
.append(" errorMsg = \"")
.append(Util.getString("GML.ThisFormContains", language))
.append("\" + errorNb + \" ")
.append(Util.getString("GML.errors", language))
.append(" :\\n \" + errorMsg;\n")
.append(" window.alert(errorMsg);\n")
.append(" result = false;\n")
.append(" break;\n")
.append(" }\n")
.append(" return result;\n")
.append("}\n")
.append(" \n\n")
.append("</script>\n");
out.flush();
jw.write(sw.toString());
} catch (java.io.IOException fe) {
SilverTrace.error("form", "AbstractForm.display", "form.EXP_CANT_WRITE", null, fe);
}
}
|
diff --git a/farrago/src/org/eigenbase/sarg/SargEndpoint.java b/farrago/src/org/eigenbase/sarg/SargEndpoint.java
index 56d12229c..37cee188c 100644
--- a/farrago/src/org/eigenbase/sarg/SargEndpoint.java
+++ b/farrago/src/org/eigenbase/sarg/SargEndpoint.java
@@ -1,465 +1,467 @@
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2006-2006 The Eigenbase Project
// Copyright (C) 2006-2006 Disruptive Tech
// Copyright (C) 2006-2006 LucidEra, 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 approved by The Eigenbase Project.
//
// 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 org.eigenbase.sarg;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.rex.*;
import org.eigenbase.util.*;
import java.util.*;
import java.math.*;
/**
* SargEndpoint represents an endpoint of a ({@link SargInterval}).
*
*<p>
*
* Instances of SargEndpoint are immutable from outside this package.
* Subclass {@link SargMutableEndpoint} is provided for manipulation
* from outside the package.
*
* @author John V. Sichi
* @version $Id$
*/
public class SargEndpoint implements Comparable<SargEndpoint>
{
// TODO jvs 16-Jan-2006: special pattern prefix support for LIKE operator
/**
* Factory which produced this endpoint.
*/
protected final SargFactory factory;
/**
* Datatype for endpoint value.
*/
protected final RelDataType dataType;
/**
* Coordinate for this endpoint,
* constrained to be either {@link RexLiteral} or {@link RexDynamicParam},
* or null to represent infinity (positive or negative infinity is
* implied by boundType).
*/
protected RexNode coordinate;
/**
* @see getBoundType
*/
protected SargBoundType boundType;
/**
* @see getStrictness
*/
protected SargStrictness strictness;
/**
* @see SargFactory.newEndpoint
*/
SargEndpoint(SargFactory factory, RelDataType dataType)
{
this.factory = factory;
this.dataType = dataType;
boundType = SargBoundType.LOWER;
strictness = SargStrictness.OPEN;
}
void copyFrom(SargEndpoint other)
{
assert(getDataType() == other.getDataType());
if (other.isFinite()) {
setFinite(
other.getBoundType(),
other.getStrictness(),
other.getCoordinate());
} else {
setInfinity(other.getInfinitude());
}
}
/**
* Sets this endpoint to either negative or positive infinity. An infinite
* endpoint implies an open bound (negative infinity implies a lower bound,
* while positive infinity implies an upper bound).
*
* @param infinitude either -1 or +1
*/
void setInfinity(int infinitude)
{
assert((infinitude == -1) || (infinitude == 1));
if (infinitude == -1) {
boundType = SargBoundType.LOWER;
} else {
boundType = SargBoundType.UPPER;
}
strictness = SargStrictness.OPEN;
coordinate = null;
}
/**
* Sets a finite value for this endpoint.
*
* @param boundType bound type (upper/lower)
*
* @param strictness boundary strictness
*
* @param coordinate endpoint position
*/
void setFinite(
SargBoundType boundType,
SargStrictness strictness,
RexNode coordinate)
{
// validate the input
assert(coordinate != null);
if (!(coordinate instanceof RexDynamicParam)) {
assert(coordinate instanceof RexLiteral);
RexLiteral literal = (RexLiteral) coordinate;
if (!RexLiteral.isNullLiteral(literal)) {
assert(SqlTypeUtil.canAssignFrom(
dataType,
literal.getType()));
}
}
this.boundType = boundType;
this.coordinate = coordinate;
this.strictness = strictness;
applyRounding();
}
private void applyRounding()
{
if (!(coordinate instanceof RexLiteral)) {
return;
}
RexLiteral literal = (RexLiteral) coordinate;
if (!(literal.getValue() instanceof BigDecimal)) {
return;
}
// For numbers, we have to deal with rounding fun and
// games.
if (SqlTypeUtil.isApproximateNumeric(dataType)) {
// REVIEW jvs 18-Jan-2006: is it necessary to do anything
// for approx types here? Wait until someone complains.
return;
}
// NOTE: defer overflow checks until cast execution. Broadbase did it
// here, but the effect should be the same. Really, instead of
// overflowing at all, right here we should convert the interval to
// either unconstrained or empty (e.g. "less than overflow value" is
// equivalent to "less than +infinity").
BigDecimal bd = (BigDecimal) literal.getValue();
BigDecimal bdRounded = bd.setScale(
dataType.getScale(),
RoundingMode.HALF_UP);
- coordinate = factory.getRexBuilder().makeExactLiteral(bdRounded);
+ coordinate = factory.getRexBuilder().makeExactLiteral(
+ bdRounded,
+ dataType);
// The sign of roundingCompensation should be the opposite of the
// rounding direction, so subtract post-rounding value from
// pre-rounding.
int roundingCompensation = bd.compareTo(bdRounded);
// rounding takes precedence over the strictness flag.
// Input round strictness output effective strictness
// >5.9 down -1 >=6 0
// >=5.9 down 0 >=6 0
// >6.1 up -1 >6 1
// >=6.1 up 0 >6 1
// <6.1 up 1 <=6 0
// <=6.1 up 0 <=6 0
// <5.9 down 1 <6 -1
// <=5.9 down 0 <6 -1
if (roundingCompensation == 0) {
return;
}
if (boundType == SargBoundType.LOWER) {
if (roundingCompensation < 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
} else if (boundType == SargBoundType.UPPER) {
if (roundingCompensation > 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
}
}
/**
* @return true if this endpoint represents a closed (exact) bound; false
* if open (strict)
*/
public boolean isClosed()
{
return strictness == SargStrictness.CLOSED;
}
/**
* @return opposite of isClosed
*/
public boolean isOpen()
{
return strictness == SargStrictness.OPEN;
}
/**
* @return true if this endpoint represents infinity (either positive or
* negative); false if a finite coordinate
*/
public boolean isFinite()
{
return coordinate != null;
}
/**
* @return -1 for negative infinity, +1 for positive infinity, 0 for
* a finite endpoint
*/
public int getInfinitude()
{
if (coordinate == null) {
if (boundType == SargBoundType.LOWER) {
return -1;
} else {
return 1;
}
} else {
return 0;
}
}
/**
* @return coordinate of this endpoint
*/
public RexNode getCoordinate()
{
return coordinate;
}
/**
* @return true if this endpoint has the null value for its coordinate
*/
public boolean isNull()
{
if (!isFinite()) {
return false;
}
return RexLiteral.isNullLiteral(coordinate);
}
/**
* @return target datatype for coordinate
*/
public RelDataType getDataType()
{
return dataType;
}
/**
* @return boundary type this endpoint represents
*/
public SargBoundType getBoundType()
{
return boundType;
}
/**
* Tests whether this endpoint "touches" another one (not necessarily
* overlapping). For example, the upper bound of the interval (1, 10)
* touches the lower bound of the interval [10, 20), but not
* of the interval (10, 20).
*
* @param other the other endpoint to test
*
* @return true if touching; false if discontinuous
*/
public boolean isTouching(SargEndpoint other)
{
assert(getDataType() == other.getDataType());
if (!isFinite() || !other.isFinite()) {
return false;
}
if ((coordinate instanceof RexDynamicParam)
|| (other.coordinate instanceof RexDynamicParam))
{
if ((coordinate instanceof RexDynamicParam)
&& (other.coordinate instanceof RexDynamicParam))
{
// make sure it's the same param
RexDynamicParam p1 = (RexDynamicParam) coordinate;
RexDynamicParam p2 = (RexDynamicParam) other.coordinate;
if (p1.getIndex() != p2.getIndex()) {
return false;
}
} else {
// one is a dynamic param but the other isn't
return false;
}
} else if (compareCoordinates(coordinate, other.coordinate) != 0) {
return false;
}
return isClosed() || other.isClosed();
}
static int compareCoordinates(RexNode coord1, RexNode coord2)
{
assert(coord1 instanceof RexLiteral);
assert(coord2 instanceof RexLiteral);
// null values always sort lowest
boolean isNull1 = RexLiteral.isNullLiteral(coord1);
boolean isNull2 = RexLiteral.isNullLiteral(coord2);
if (isNull1 && isNull2) {
return 0;
} else if (isNull1) {
return -1;
} else if (isNull2) {
return 1;
} else {
RexLiteral lit1 = (RexLiteral) coord1;
RexLiteral lit2 = (RexLiteral) coord2;
return lit1.getValue().compareTo(lit2.getValue());
}
}
// implement Object
public String toString()
{
if (coordinate == null) {
if (boundType == SargBoundType.LOWER) {
return "-infinity";
} else {
return "+infinity";
}
}
StringBuilder sb = new StringBuilder();
if (boundType == SargBoundType.LOWER) {
if (isClosed()) {
sb.append(">=");
} else {
sb.append(">");
}
} else {
if (isClosed()) {
sb.append("<=");
} else {
sb.append("<");
}
}
sb.append(" ");
sb.append(coordinate);
return sb.toString();
}
// implement Comparable
public int compareTo(SargEndpoint other)
{
if (getInfinitude() != other.getInfinitude()) {
// at least one is infinite; result is based on comparison of
// infinitudes
return getInfinitude() - other.getInfinitude();
}
if (!isFinite()) {
// both are the same infinity: equals
return 0;
}
// both are finite: compare coordinates
int c = compareCoordinates(
getCoordinate(), other.getCoordinate());
if (c != 0) {
return c;
}
// if coordinates are the same, then result is based on comparison of
// strictness
return getStrictnessSign() - other.getStrictnessSign();
}
/**
* @return SargStrictness of this bound
*/
public SargStrictness getStrictness()
{
return strictness;
}
/**
* @return complement of SargStrictness of this bound
*/
public SargStrictness getStrictnessComplement()
{
return (strictness == SargStrictness.OPEN)
? SargStrictness.CLOSED
: SargStrictness.OPEN;
}
/**
* @return -1 for infinitesimally below (open upper bound,
* strictly less than), 0 for exact equality (closed bound), 1 for
* infinitesimally above (open lower bound, strictly greater than)
*/
public int getStrictnessSign()
{
if (strictness == SargStrictness.CLOSED) {
return 0;
} else {
if (boundType == SargBoundType.LOWER) {
return 1;
} else {
return -1;
}
}
}
// override Object
public boolean equals(Object other)
{
if (!(other instanceof SargEndpoint)) {
return false;
}
return compareTo((SargEndpoint) other) == 0;
}
// override Object
public int hashCode()
{
return toString().hashCode();
}
}
// End SargEndpoint.java
| true | true | private void applyRounding()
{
if (!(coordinate instanceof RexLiteral)) {
return;
}
RexLiteral literal = (RexLiteral) coordinate;
if (!(literal.getValue() instanceof BigDecimal)) {
return;
}
// For numbers, we have to deal with rounding fun and
// games.
if (SqlTypeUtil.isApproximateNumeric(dataType)) {
// REVIEW jvs 18-Jan-2006: is it necessary to do anything
// for approx types here? Wait until someone complains.
return;
}
// NOTE: defer overflow checks until cast execution. Broadbase did it
// here, but the effect should be the same. Really, instead of
// overflowing at all, right here we should convert the interval to
// either unconstrained or empty (e.g. "less than overflow value" is
// equivalent to "less than +infinity").
BigDecimal bd = (BigDecimal) literal.getValue();
BigDecimal bdRounded = bd.setScale(
dataType.getScale(),
RoundingMode.HALF_UP);
coordinate = factory.getRexBuilder().makeExactLiteral(bdRounded);
// The sign of roundingCompensation should be the opposite of the
// rounding direction, so subtract post-rounding value from
// pre-rounding.
int roundingCompensation = bd.compareTo(bdRounded);
// rounding takes precedence over the strictness flag.
// Input round strictness output effective strictness
// >5.9 down -1 >=6 0
// >=5.9 down 0 >=6 0
// >6.1 up -1 >6 1
// >=6.1 up 0 >6 1
// <6.1 up 1 <=6 0
// <=6.1 up 0 <=6 0
// <5.9 down 1 <6 -1
// <=5.9 down 0 <6 -1
if (roundingCompensation == 0) {
return;
}
if (boundType == SargBoundType.LOWER) {
if (roundingCompensation < 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
} else if (boundType == SargBoundType.UPPER) {
if (roundingCompensation > 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
}
}
| private void applyRounding()
{
if (!(coordinate instanceof RexLiteral)) {
return;
}
RexLiteral literal = (RexLiteral) coordinate;
if (!(literal.getValue() instanceof BigDecimal)) {
return;
}
// For numbers, we have to deal with rounding fun and
// games.
if (SqlTypeUtil.isApproximateNumeric(dataType)) {
// REVIEW jvs 18-Jan-2006: is it necessary to do anything
// for approx types here? Wait until someone complains.
return;
}
// NOTE: defer overflow checks until cast execution. Broadbase did it
// here, but the effect should be the same. Really, instead of
// overflowing at all, right here we should convert the interval to
// either unconstrained or empty (e.g. "less than overflow value" is
// equivalent to "less than +infinity").
BigDecimal bd = (BigDecimal) literal.getValue();
BigDecimal bdRounded = bd.setScale(
dataType.getScale(),
RoundingMode.HALF_UP);
coordinate = factory.getRexBuilder().makeExactLiteral(
bdRounded,
dataType);
// The sign of roundingCompensation should be the opposite of the
// rounding direction, so subtract post-rounding value from
// pre-rounding.
int roundingCompensation = bd.compareTo(bdRounded);
// rounding takes precedence over the strictness flag.
// Input round strictness output effective strictness
// >5.9 down -1 >=6 0
// >=5.9 down 0 >=6 0
// >6.1 up -1 >6 1
// >=6.1 up 0 >6 1
// <6.1 up 1 <=6 0
// <=6.1 up 0 <=6 0
// <5.9 down 1 <6 -1
// <=5.9 down 0 <6 -1
if (roundingCompensation == 0) {
return;
}
if (boundType == SargBoundType.LOWER) {
if (roundingCompensation < 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
} else if (boundType == SargBoundType.UPPER) {
if (roundingCompensation > 0) {
strictness = SargStrictness.CLOSED;
} else {
strictness = SargStrictness.OPEN;
}
}
}
|
diff --git a/src/main/java/com/thevoxelbox/voxelbar/VoxelBar.java b/src/main/java/com/thevoxelbox/voxelbar/VoxelBar.java
index b9aaaef..0ced938 100644
--- a/src/main/java/com/thevoxelbox/voxelbar/VoxelBar.java
+++ b/src/main/java/com/thevoxelbox/voxelbar/VoxelBar.java
@@ -1,31 +1,31 @@
package com.thevoxelbox.voxelbar;
import java.util.*;
import org.bukkit.plugin.java.JavaPlugin;
public class VoxelBar extends JavaPlugin {
private static VoxelBar instance;
public static VoxelBar getInstance() {
return instance;
}
@Override
public void onDisable() {
VoxelBarToggleManager.savePlayers(); // save player settings to config
}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(new VoxelBarListener(), this); // Register VoxelBarListener
getCommand("vbar").setExecutor(new VoxelBarCommands()); // Register VoxelBarCommands
- saveDefaultConfig(); // create config if not created already
+ saveConfig(); // create config if not created already
VoxelBarToggleManager.loadPlayers(); // Load players settings from the config
}
}
| true | true | public void onEnable() {
getServer().getPluginManager().registerEvents(new VoxelBarListener(), this); // Register VoxelBarListener
getCommand("vbar").setExecutor(new VoxelBarCommands()); // Register VoxelBarCommands
saveDefaultConfig(); // create config if not created already
VoxelBarToggleManager.loadPlayers(); // Load players settings from the config
}
| public void onEnable() {
getServer().getPluginManager().registerEvents(new VoxelBarListener(), this); // Register VoxelBarListener
getCommand("vbar").setExecutor(new VoxelBarCommands()); // Register VoxelBarCommands
saveConfig(); // create config if not created already
VoxelBarToggleManager.loadPlayers(); // Load players settings from the config
}
|
diff --git a/android/src/com/henrikrydgard/libnative/NativeActivity.java b/android/src/com/henrikrydgard/libnative/NativeActivity.java
index e0d6967..d515207 100644
--- a/android/src/com/henrikrydgard/libnative/NativeActivity.java
+++ b/android/src/com/henrikrydgard/libnative/NativeActivity.java
@@ -1,707 +1,707 @@
package com.henrikrydgard.libnative;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ConfigurationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
// We can't even open a file for writing? Then we can't get a unique-ish installation id.
return "BROKENAPPUSERFILESYSTEM";
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
public class NativeActivity extends Activity {
// Remember to loadLibrary your JNI .so in a static {} block
// Adjust these as necessary
private static String TAG = "NativeActivity";
// Allows us to skip a lot of initialization on secondary calls to onCreate.
private static boolean initialized = false;
// Graphics and audio interfaces
private NativeGLView mGLSurfaceView;
private NativeAudioPlayer audioPlayer;
private NativeRenderer nativeRenderer;
boolean useOpenSL = false;
public static String runCommand;
public static String commandParameter;
public static String installID;
// Remember settings for best audio latency
private int optimalFramesPerBuffer;
private int optimalSampleRate;
// audioFocusChangeListener to listen to changes in audio state
private AudioFocusChangeListener audioFocusChangeListener;
private AudioManager audioManager;
private Vibrator vibrator;
public static boolean inputBoxCancelled;
// Allow for two connected gamepads but just consider them the same for now.
// Actually this is not entirely true, see the code.
InputDeviceState inputPlayerA;
InputDeviceState inputPlayerB;
String inputPlayerADesc;
@TargetApi(17)
private void detectOptimalAudioSettings() {
try {
optimalFramesPerBuffer = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
optimalSampleRate = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
} catch (NumberFormatException e) {
// Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it).
}
}
String getApplicationLibraryDir(ApplicationInfo application) {
String libdir = null;
try {
// Starting from Android 2.3, nativeLibraryDir is available:
Field field = ApplicationInfo.class.getField("nativeLibraryDir");
libdir = (String) field.get(application);
} catch (SecurityException e1) {
} catch (NoSuchFieldException e1) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
if (libdir == null) {
// Fallback for Android < 2.3:
libdir = application.dataDir + "/lib";
}
return libdir;
}
@TargetApi(13)
void GetScreenSizeHC(Point size) {
WindowManager w = getWindowManager();
w.getDefaultDisplay().getSize(size);
}
void GetScreenSize(Point size) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
GetScreenSizeHC(size);
} else {
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
size.x = d.getWidth();
size.y = d.getHeight();
}
}
public void Initialize() {
//initialise audio classes. Do this here since detectOptimalAudioSettings()
//needs audioManager
this.audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
this.audioFocusChangeListener = new AudioFocusChangeListener();
if (Build.VERSION.SDK_INT >= 9) {
// Native OpenSL is available. Let's use it!
useOpenSL = true;
}
if (Build.VERSION.SDK_INT >= 17) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
/*
if (NativeApp.isLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}*/
Log.i(TAG, "onCreate");
// Get system information
ApplicationInfo appInfo = null;
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String libraryDir = getApplicationLibraryDir(appInfo);
File sdcard = Environment.getExternalStorageDirectory();
Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
@SuppressWarnings("deprecation")
int scrPixelFormat = display.getPixelFormat();
Point size = new Point();
GetScreenSize(size);
int scrWidth = size.x;
int scrHeight = size.y;
float scrRefreshRate = display.getRefreshRate();
String externalStorageDir = sdcard.getAbsolutePath();
String dataDir = this.getFilesDir().getAbsolutePath();
String apkFilePath = appInfo.sourceDir;
NativeApp.sendMessage("Message from Java", "Hot Coffee");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int dpi = metrics.densityDpi;
// We only use dpi to calculate the width. Smaller aspect ratios have giant text despite high DPI.
- dpi = dpi * ((float)srcWidth/(float)srcHeight) / (16.0/9.0); // Adjust to 16:9
+ dpi = (int)((float)dpi * ((float)scrWidth/(float)scrHeight) / (16.0/9.0)); // Adjust to 16:9
String deviceType = Build.MANUFACTURER + ":" + Build.MODEL;
String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
// INIT!
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(dpi, deviceType, languageRegion, apkFilePath, dataDir, externalStorageDir, libraryDir, installID, useOpenSL);
Log.i(TAG, "Device: " + deviceType);
Log.i(TAG, "W : " + scrWidth + " H: " + scrHeight + " rate: " + scrRefreshRate + " fmt: " + scrPixelFormat + " dpi: " + dpi);
// Detect OpenGL support.
// We don't currently use this detection for anything but good to have in the log.
if (!detectOpenGLES20()) {
Log.i(TAG, "OpenGL ES 2.0 NOT detected. Things will likely go badly.");
} else {
if (detectOpenGLES30()) {
Log.i(TAG, "OpenGL ES 3.0 detected.");
}
else {
Log.i(TAG, "OpenGL ES 2.0 detected.");
}
}
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= 11) {
checkForVibrator();
}
/*
editText = new EditText(this);
editText.setText("Hello world");
addContentView(editText, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
*/
// inputBox("Please ener a s", "", "Save");
}
// Need API 11 to check for existence of a vibrator? Zany.
@TargetApi(11)
public void checkForVibrator() {
if (Build.VERSION.SDK_INT >= 11) {
if (!vibrator.hasVibrator()) {
vibrator = null;
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
installID = Installation.id(this);
if (!initialized) {
Initialize();
initialized = true;
}
// Keep the screen bright - very annoying if it goes dark when tilting away
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Initialize audio and tell PPSSPP to gain audio focus
if (!useOpenSL) {
audioPlayer = new NativeAudioPlayer();
}
NativeAudioPlayer.gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.audioInit();
mGLSurfaceView = new NativeGLView(this);
mGLSurfaceView.setEGLContextClientVersion(2);
// Setup the GLSurface and ask android for the correct
// Number of bits for r, g, b, a, depth and stencil components
// The PSP only has 16-bit Z so that should be enough.
// Might want to change this for other apps (24-bit might be useful).
// Actually, we might be able to do without both stencil and depth in
// the back buffer, but that would kill non-buffered rendering.
// It appears some gingerbread devices blow up if you use a config chooser at all ???? (Xperia Play)
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// On some (especially older devices), things blow up later (EGL_BAD_MATCH) if we don't set the format here,
// if we specify that we want destination alpha in the config chooser, which we do.
// http://grokbase.com/t/gg/android-developers/11bj40jm4w/fall-back
mGLSurfaceView.getHolder().setFormat(PixelFormat.RGBX_8888);
mGLSurfaceView.setEGLConfigChooser(new NativeEGLConfigChooser());
nativeRenderer = new NativeRenderer(this);
mGLSurfaceView.setRenderer(nativeRenderer);
setContentView(mGLSurfaceView);
if (Build.VERSION.SDK_INT >= 14) {
darkenOnScreenButtons();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setImmersiveMode();
}
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop - do nothing, just let Android switch away");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
mGLSurfaceView.onDestroy();
nativeRenderer.onDestroyed();
NativeApp.audioShutdown();
// Probably vain attempt to help the garbage collector...
audioPlayer = null;
mGLSurfaceView = null;
audioFocusChangeListener = null;
audioManager = null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void darkenOnScreenButtons() {
mGLSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setImmersiveMode() {
this.setImmersive(true); // This is an entirely different kind of immersive mode - hides some notification
mGLSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
private boolean detectOpenGLES20() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
return info.reqGlEsVersion >= 0x20000;
}
private boolean detectOpenGLES30() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
return info.reqGlEsVersion >= 0x30000;
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
NativeAudioPlayer.loseAudioFocus(this.audioManager, this.audioFocusChangeListener);
if (audioPlayer != null) {
audioPlayer.stop();
}
Log.i(TAG, "nativeapp pause");
NativeApp.pause();
Log.i(TAG, "gl pause");
mGLSurfaceView.onPause();
Log.i(TAG, "onPause returning");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
if (mGLSurfaceView != null) {
mGLSurfaceView.onResume();
} else {
Log.e(TAG, "mGLSurfaceView really shouldn't be null in onResume");
}
NativeAudioPlayer.gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
if (audioPlayer != null) {
audioPlayer.play();
}
NativeApp.resume();
if (Build.VERSION.SDK_INT >= 14) {
darkenOnScreenButtons();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setImmersiveMode();
}
}
// Prevent destroying and recreating the main activity when the device rotates etc,
// since this would stop the sound.
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Ignore orientation change
super.onConfigurationChanged(newConfig);
}
// We simply grab the first input device to produce an event and ignore all others that are connected.
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private InputDeviceState getInputDeviceState(InputEvent event) {
InputDevice device = event.getDevice();
if (device == null) {
return null;
}
if (inputPlayerA == null) {
Log.i(TAG, "Input player A registered");
inputPlayerA = new InputDeviceState(device);
inputPlayerADesc = getInputDesc(device);
}
if (inputPlayerA.getDevice() == device) {
return inputPlayerA;
}
if (inputPlayerB == null) {
Log.i(TAG, "Input player B registered");
inputPlayerB = new InputDeviceState(device);
}
if (inputPlayerB.getDevice() == device) {
return inputPlayerB;
}
return inputPlayerA;
}
// We grab the keys before onKeyDown/... even see them. This is also better because it lets us
// distinguish devices.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
return super.dispatchKeyEvent(event);
}
// Let's let volume and back through to dispatchKeyEvent.
boolean passThrough = false;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_MUTE:
case KeyEvent.KEYCODE_MENU:
passThrough = true;
break;
default:
break;
}
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (state.onKeyDown(event) && !passThrough) {
return true;
}
break;
case KeyEvent.ACTION_UP:
if (state.onKeyUp(event) && !passThrough) {
return true;
}
break;
}
}
// Let's go through the old path (onKeyUp, onKeyDown).
return super.dispatchKeyEvent(event);
}
@TargetApi(16)
static public String getInputDesc(InputDevice input) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return input.getDescriptor();
} else {
List<InputDevice.MotionRange> motions = input.getMotionRanges();
String fakeid = "";
for (InputDevice.MotionRange range : motions)
fakeid += range.getAxis();
return fakeid;
}
}
@Override
@TargetApi(12)
public boolean onGenericMotionEvent(MotionEvent event) {
// Log.d(TAG, "onGenericMotionEvent: " + event);
if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
if (Build.VERSION.SDK_INT >= 12) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
Log.w(TAG, "Joystick event but failed to get input device state.");
return super.onGenericMotionEvent(event);
}
state.onJoystickMotion(event);
return true;
}
}
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_MOVE:
// process the mouse hover movement...
return true;
case MotionEvent.ACTION_SCROLL:
NativeApp.mouseWheelEvent(event.getX(), event.getY());
return true;
}
}
return super.onGenericMotionEvent(event);
}
@SuppressLint("NewApi")
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Eat these keys, to avoid accidental exits / other screwups.
// Maybe there's even more we need to eat on tablets?
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyDown(0, 1004); // special custom keycode
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
return super.onKeyDown(keyCode, event);
} else {
NativeApp.keyDown(0, keyCode);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
NativeApp.keyDown(0, keyCode);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
// NativeApp should ignore these.
return super.onKeyDown(keyCode, event);
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyDown(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
NativeApp.keyDown(0, keyCode);
return true;
}
}
@SuppressLint("NewApi")
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyUp(0, 1004); // special custom keycode
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
return super.onKeyUp(keyCode, event);
} else {
NativeApp.keyUp(0, keyCode);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
// Search probably should also be ignored. We send it to the app.
NativeApp.keyUp(0, keyCode);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
return super.onKeyUp(keyCode, event);
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyUp(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
NativeApp.keyUp(0, keyCode);
return true;
}
}
public String inputBox(String title, String defaultText, String defaultAction) {
final FrameLayout fl = new FrameLayout(this);
final EditText input = new EditText(this);
input.setGravity(Gravity.CENTER);
inputBoxCancelled = false;
FrameLayout.LayoutParams editBoxLayout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
editBoxLayout.setMargins(2, 20, 2, 20);
fl.addView(input, editBoxLayout);
input.setText(defaultText);
input.selectAll();
AlertDialog dlg = new AlertDialog.Builder(this)
.setView(fl)
.setTitle(title)
.setPositiveButton(defaultAction, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int which) {
d.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int which) {
d.cancel();
NativeActivity.inputBoxCancelled = false;
}
}).create();
dlg.setCancelable(false);
dlg.show();
if (inputBoxCancelled)
return null;
NativeApp.sendMessage("INPUTBOX:" + title, input.getText().toString());
return input.getText().toString();
}
public void processCommand(String command, String params) {
if (command.equals("launchBrowser")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(params));
startActivity(i);
} else if (command.equals("launchEmail")) {
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText;
uriText = "mailto:[email protected]" +
"?subject=Your app is..." +
"&body=great! Or?";
uriText = uriText.replace(" ", "%20");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "E-mail the app author!"));
} else if (command.equals("launchMarket")) {
// Don't need this, can just use launchBrowser with a market:
// http://stackoverflow.com/questions/3442366/android-link-to-market-from-inside-another-app
// http://developer.android.com/guide/publishing/publishing.html#marketintent
} else if (command.equals("toast")) {
Toast toast = Toast.makeText(this, params, Toast.LENGTH_SHORT);
toast.show();
} else if (command.equals("showKeyboard")) {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// No idea what the point of the ApplicationWindowToken is or if it matters where we get it from...
inputMethodManager.toggleSoftInputFromWindow(mGLSurfaceView.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
} else if (command.equals("hideKeyboard")) {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(mGLSurfaceView.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
} else if (command.equals("inputBox")) {
inputBox(params, "", "OK");
} else if (command.equals("vibrate")) {
if (vibrator != null) {
int milliseconds = -1;
if (params != "") {
try {
milliseconds = Integer.parseInt(params);
} catch (NumberFormatException e) {
}
}
// Special parameters to perform standard haptic feedback operations
// -1 = Standard keyboard press feedback
// -2 = Virtual key press
// -3 = Long press feedback
// Note that these three do not require the VIBRATE Android permission.
switch (milliseconds) {
case -1:
mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
break;
case -2:
mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
break;
case -3:
mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
break;
default:
vibrator.vibrate(milliseconds);
break;
}
}
} else {
Log.e(TAG, "Unsupported command " + command + " , param: " + params);
}
}
}
| true | true | public void Initialize() {
//initialise audio classes. Do this here since detectOptimalAudioSettings()
//needs audioManager
this.audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
this.audioFocusChangeListener = new AudioFocusChangeListener();
if (Build.VERSION.SDK_INT >= 9) {
// Native OpenSL is available. Let's use it!
useOpenSL = true;
}
if (Build.VERSION.SDK_INT >= 17) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
/*
if (NativeApp.isLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}*/
Log.i(TAG, "onCreate");
// Get system information
ApplicationInfo appInfo = null;
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String libraryDir = getApplicationLibraryDir(appInfo);
File sdcard = Environment.getExternalStorageDirectory();
Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
@SuppressWarnings("deprecation")
int scrPixelFormat = display.getPixelFormat();
Point size = new Point();
GetScreenSize(size);
int scrWidth = size.x;
int scrHeight = size.y;
float scrRefreshRate = display.getRefreshRate();
String externalStorageDir = sdcard.getAbsolutePath();
String dataDir = this.getFilesDir().getAbsolutePath();
String apkFilePath = appInfo.sourceDir;
NativeApp.sendMessage("Message from Java", "Hot Coffee");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int dpi = metrics.densityDpi;
// We only use dpi to calculate the width. Smaller aspect ratios have giant text despite high DPI.
dpi = dpi * ((float)srcWidth/(float)srcHeight) / (16.0/9.0); // Adjust to 16:9
String deviceType = Build.MANUFACTURER + ":" + Build.MODEL;
String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
// INIT!
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(dpi, deviceType, languageRegion, apkFilePath, dataDir, externalStorageDir, libraryDir, installID, useOpenSL);
Log.i(TAG, "Device: " + deviceType);
Log.i(TAG, "W : " + scrWidth + " H: " + scrHeight + " rate: " + scrRefreshRate + " fmt: " + scrPixelFormat + " dpi: " + dpi);
// Detect OpenGL support.
// We don't currently use this detection for anything but good to have in the log.
if (!detectOpenGLES20()) {
Log.i(TAG, "OpenGL ES 2.0 NOT detected. Things will likely go badly.");
} else {
if (detectOpenGLES30()) {
Log.i(TAG, "OpenGL ES 3.0 detected.");
}
else {
Log.i(TAG, "OpenGL ES 2.0 detected.");
}
}
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= 11) {
checkForVibrator();
}
/*
editText = new EditText(this);
editText.setText("Hello world");
addContentView(editText, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
*/
// inputBox("Please ener a s", "", "Save");
}
| public void Initialize() {
//initialise audio classes. Do this here since detectOptimalAudioSettings()
//needs audioManager
this.audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
this.audioFocusChangeListener = new AudioFocusChangeListener();
if (Build.VERSION.SDK_INT >= 9) {
// Native OpenSL is available. Let's use it!
useOpenSL = true;
}
if (Build.VERSION.SDK_INT >= 17) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
/*
if (NativeApp.isLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}*/
Log.i(TAG, "onCreate");
// Get system information
ApplicationInfo appInfo = null;
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String libraryDir = getApplicationLibraryDir(appInfo);
File sdcard = Environment.getExternalStorageDirectory();
Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
@SuppressWarnings("deprecation")
int scrPixelFormat = display.getPixelFormat();
Point size = new Point();
GetScreenSize(size);
int scrWidth = size.x;
int scrHeight = size.y;
float scrRefreshRate = display.getRefreshRate();
String externalStorageDir = sdcard.getAbsolutePath();
String dataDir = this.getFilesDir().getAbsolutePath();
String apkFilePath = appInfo.sourceDir;
NativeApp.sendMessage("Message from Java", "Hot Coffee");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int dpi = metrics.densityDpi;
// We only use dpi to calculate the width. Smaller aspect ratios have giant text despite high DPI.
dpi = (int)((float)dpi * ((float)scrWidth/(float)scrHeight) / (16.0/9.0)); // Adjust to 16:9
String deviceType = Build.MANUFACTURER + ":" + Build.MODEL;
String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
// INIT!
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(dpi, deviceType, languageRegion, apkFilePath, dataDir, externalStorageDir, libraryDir, installID, useOpenSL);
Log.i(TAG, "Device: " + deviceType);
Log.i(TAG, "W : " + scrWidth + " H: " + scrHeight + " rate: " + scrRefreshRate + " fmt: " + scrPixelFormat + " dpi: " + dpi);
// Detect OpenGL support.
// We don't currently use this detection for anything but good to have in the log.
if (!detectOpenGLES20()) {
Log.i(TAG, "OpenGL ES 2.0 NOT detected. Things will likely go badly.");
} else {
if (detectOpenGLES30()) {
Log.i(TAG, "OpenGL ES 3.0 detected.");
}
else {
Log.i(TAG, "OpenGL ES 2.0 detected.");
}
}
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= 11) {
checkForVibrator();
}
/*
editText = new EditText(this);
editText.setText("Hello world");
addContentView(editText, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
*/
// inputBox("Please ener a s", "", "Save");
}
|
diff --git a/src/main/java/jetbrick/schema/app/reader/ColumnUtils.java b/src/main/java/jetbrick/schema/app/reader/ColumnUtils.java
index 222189f..4b661eb 100644
--- a/src/main/java/jetbrick/schema/app/reader/ColumnUtils.java
+++ b/src/main/java/jetbrick/schema/app/reader/ColumnUtils.java
@@ -1,150 +1,154 @@
package jetbrick.schema.app.reader;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.util.List;
import jetbrick.commons.bean.ClassConvertUtils;
import jetbrick.commons.exception.SystemException;
import jetbrick.commons.lang.CamelCaseUtils;
import jetbrick.commons.xml.XmlAttribute;
import jetbrick.commons.xml.XmlNode;
import jetbrick.dao.dialect.SqlType;
import jetbrick.dao.dialect.SubStyleType;
import jetbrick.dao.schema.validator.Validator;
import jetbrick.dao.schema.validator.ValidatorFactory;
import jetbrick.schema.app.model.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
public class ColumnUtils {
public static void addDefaultPrimaryKey(TableInfo table, String typeName) {
if (StringUtils.isBlank(typeName)) {
typeName = table.getSchema().getProperty("primary.key.type");
}
if (StringUtils.isBlank(typeName)) {
typeName = SubStyleType.UID;
}
SqlType type = SqlType.newInstance(typeName);
TableColumn c = new TableColumn();
c.setTable(table);
c.setFieldName("id");
c.setFieldClass(SubStyleType.getJavaClass(type.getName()));
c.setColumnName("id");
c.setTypeName(type.getName());
c.setTypeLength(type.getLength());
c.setTypeScale(type.getScale());
c.setNullable(false);
c.setDefaultValue(null);
c.setDisplayName("ID");
c.setDescription(null);
c.setPrimaryKey(true);
c.setJson(true);
table.addColumn(c);
table.getPrimaryKey().setColumn(c);
}
public static void mappingColumnList(TableInfo table, XmlNode root) {
for (XmlNode node : root.elements("column")) {
TableColumn c = mappingSchemaColumn(table, node);
table.addColumn(c);
// process enum
if (SubStyleType.ENUM.equals(c.getTypeName())) {
Integer ref = node.attribute("enum-group-ref").asInt();
EnumGroup enumGroup;
if (ref != null) {
enumGroup = table.getSchema().getReferenceEnumGroup(ref);
if (enumGroup == null) {
String error = String.format("Enum group reference %d is not found in %s.%s.", ref, table.getTableName(), c.getColumnName());
throw new RuntimeException(error);
}
} else {
node = node.element("enum-group");
if (node == null) {
String error = String.format("Missing enum-group node for %s.%s.", table.getTableName(), c.getColumnName());
throw new RuntimeException(error);
}
enumGroup = EnumFileUtils.createSchemaEnumGroup(table.getSchema(), node);
}
enumGroup.setIdentifier(table.getTableClass() + "_" + CamelCaseUtils.toCapitalizeCamelCase(c.getColumnName()));
enumGroup.setDescription(table.getDisplayName() + "->" + c.getDisplayName());
c.setEnumGroup(enumGroup);
}
}
}
public static TableColumn mappingSchemaColumn(TableInfo table, XmlNode node) {
TableColumn c = new TableColumn();
c.setTable(table);
c.setColumnName(node.attribute("name").asString());
c.setNullable(node.attribute("nullable").asBool(false));
c.setDisplayName(node.attribute("display-name").asString());
c.setDescription(node.attribute("description").asString());
c.setJson(node.attribute("json").asBool(true));
String typeName = node.attribute("type").asString().toLowerCase();
+ String aliasTypeName = table.getSchema().getTypeNameAlias().getProperty(typeName);
+ if (aliasTypeName != null) {
+ typeName = aliasTypeName;
+ }
SqlType type = SqlType.newInstance(typeName);
c.setTypeName(type.getName());
c.setTypeLength(type.getLength());
c.setTypeScale(type.getScale());
c.setFieldName(CamelCaseUtils.toCamelCase(c.getColumnName()));
c.setFieldClass(SubStyleType.getJavaClass(type.getName()));
String defaultValue = node.attribute("default").asString();
if (defaultValue != null) {
c.setDefaultValue(ClassConvertUtils.convert(defaultValue, c.getFieldClass()));
}
Class<?> typeClass = c.getFieldClass();
if (byte[].class.equals(typeClass)) {
c.setJson(false);
} else if (InputStream.class.equals(typeClass)) {
c.setJson(false);
} else if (Clob.class.equals(typeClass)) {
c.setJson(false);
} else if (Blob.class.equals(typeClass)) {
c.setJson(false);
}
if ("id".equals(c.getColumnName())) {
throw new SystemException("id is duplicated with primary key for " + table.getTableName());
}
// 外键引用
XmlNode ref = node.element("one-to-many");
if (ref != null) {
String refTable = ref.attribute("reference-table").asString();
String importName = ref.attribute("import-name").asString();
String exportName = ref.attribute("export-name").asString();
OneToManyUtils.add(c, refTable, importName, exportName);
}
// support validator
XmlNode validators = node.element("validators");
if (validators == null) return c;
for (XmlNode n : validators.elements()) {
String validatorName = n.name();
Validator validator = ValidatorFactory.createValidator(validatorName);
if (validator == null) {
throw new SystemException("Invalid validator found at %s: %s.", c.getColumnName(), validatorName);
}
for (XmlAttribute attr : (List<XmlAttribute>) n.attributes()) {
try {
BeanUtils.setProperty(validator, attr.name(), attr.value());
} catch (Exception e) {
throw SystemException.unchecked(e);
}
}
c.getValidators().add(validator);
}
return c;
}
}
| true | true | public static TableColumn mappingSchemaColumn(TableInfo table, XmlNode node) {
TableColumn c = new TableColumn();
c.setTable(table);
c.setColumnName(node.attribute("name").asString());
c.setNullable(node.attribute("nullable").asBool(false));
c.setDisplayName(node.attribute("display-name").asString());
c.setDescription(node.attribute("description").asString());
c.setJson(node.attribute("json").asBool(true));
String typeName = node.attribute("type").asString().toLowerCase();
SqlType type = SqlType.newInstance(typeName);
c.setTypeName(type.getName());
c.setTypeLength(type.getLength());
c.setTypeScale(type.getScale());
c.setFieldName(CamelCaseUtils.toCamelCase(c.getColumnName()));
c.setFieldClass(SubStyleType.getJavaClass(type.getName()));
String defaultValue = node.attribute("default").asString();
if (defaultValue != null) {
c.setDefaultValue(ClassConvertUtils.convert(defaultValue, c.getFieldClass()));
}
Class<?> typeClass = c.getFieldClass();
if (byte[].class.equals(typeClass)) {
c.setJson(false);
} else if (InputStream.class.equals(typeClass)) {
c.setJson(false);
} else if (Clob.class.equals(typeClass)) {
c.setJson(false);
} else if (Blob.class.equals(typeClass)) {
c.setJson(false);
}
if ("id".equals(c.getColumnName())) {
throw new SystemException("id is duplicated with primary key for " + table.getTableName());
}
// 外键引用
XmlNode ref = node.element("one-to-many");
if (ref != null) {
String refTable = ref.attribute("reference-table").asString();
String importName = ref.attribute("import-name").asString();
String exportName = ref.attribute("export-name").asString();
OneToManyUtils.add(c, refTable, importName, exportName);
}
// support validator
XmlNode validators = node.element("validators");
if (validators == null) return c;
for (XmlNode n : validators.elements()) {
String validatorName = n.name();
Validator validator = ValidatorFactory.createValidator(validatorName);
if (validator == null) {
throw new SystemException("Invalid validator found at %s: %s.", c.getColumnName(), validatorName);
}
for (XmlAttribute attr : (List<XmlAttribute>) n.attributes()) {
try {
BeanUtils.setProperty(validator, attr.name(), attr.value());
} catch (Exception e) {
throw SystemException.unchecked(e);
}
}
c.getValidators().add(validator);
}
return c;
}
| public static TableColumn mappingSchemaColumn(TableInfo table, XmlNode node) {
TableColumn c = new TableColumn();
c.setTable(table);
c.setColumnName(node.attribute("name").asString());
c.setNullable(node.attribute("nullable").asBool(false));
c.setDisplayName(node.attribute("display-name").asString());
c.setDescription(node.attribute("description").asString());
c.setJson(node.attribute("json").asBool(true));
String typeName = node.attribute("type").asString().toLowerCase();
String aliasTypeName = table.getSchema().getTypeNameAlias().getProperty(typeName);
if (aliasTypeName != null) {
typeName = aliasTypeName;
}
SqlType type = SqlType.newInstance(typeName);
c.setTypeName(type.getName());
c.setTypeLength(type.getLength());
c.setTypeScale(type.getScale());
c.setFieldName(CamelCaseUtils.toCamelCase(c.getColumnName()));
c.setFieldClass(SubStyleType.getJavaClass(type.getName()));
String defaultValue = node.attribute("default").asString();
if (defaultValue != null) {
c.setDefaultValue(ClassConvertUtils.convert(defaultValue, c.getFieldClass()));
}
Class<?> typeClass = c.getFieldClass();
if (byte[].class.equals(typeClass)) {
c.setJson(false);
} else if (InputStream.class.equals(typeClass)) {
c.setJson(false);
} else if (Clob.class.equals(typeClass)) {
c.setJson(false);
} else if (Blob.class.equals(typeClass)) {
c.setJson(false);
}
if ("id".equals(c.getColumnName())) {
throw new SystemException("id is duplicated with primary key for " + table.getTableName());
}
// 外键引用
XmlNode ref = node.element("one-to-many");
if (ref != null) {
String refTable = ref.attribute("reference-table").asString();
String importName = ref.attribute("import-name").asString();
String exportName = ref.attribute("export-name").asString();
OneToManyUtils.add(c, refTable, importName, exportName);
}
// support validator
XmlNode validators = node.element("validators");
if (validators == null) return c;
for (XmlNode n : validators.elements()) {
String validatorName = n.name();
Validator validator = ValidatorFactory.createValidator(validatorName);
if (validator == null) {
throw new SystemException("Invalid validator found at %s: %s.", c.getColumnName(), validatorName);
}
for (XmlAttribute attr : (List<XmlAttribute>) n.attributes()) {
try {
BeanUtils.setProperty(validator, attr.name(), attr.value());
} catch (Exception e) {
throw SystemException.unchecked(e);
}
}
c.getValidators().add(validator);
}
return c;
}
|
diff --git a/srcj/com/sun/electric/tool/user/ui/VectorDrawing.java b/srcj/com/sun/electric/tool/user/ui/VectorDrawing.java
index 353fd3653..e2f94e0ee 100644
--- a/srcj/com/sun/electric/tool/user/ui/VectorDrawing.java
+++ b/srcj/com/sun/electric/tool/user/ui/VectorDrawing.java
@@ -1,1985 +1,1985 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: VectorDrawing.java
*
* Copyright (c) 2005 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.ui;
import com.sun.electric.Main;
import com.sun.electric.database.CellUsage;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.GenMath.MutableDouble;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.MutableTextDescriptor;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.Job;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Class to do rapid redraw by caching the vector coordinates of all objects.
*/
public class VectorDrawing
{
private static final boolean TAKE_STATS = false;
private static final boolean DEBUGIMAGES = false;
private static final int MAXGREEKSIZE = 25;
/** the EditWindow being drawn */ private EditWindow wnd;
/** the rendering object */ private PixelDrawing offscreen;
/** the window scale */ private float scale;
/** the window offset */ private float offX, offY;
/** the window scale and pan factor */ private float factorX, factorY;
/** true if "peeking" and expanding to the bottom */ private boolean fullInstantiate;
/** time that rendering started */ private long startTime;
/** true if the user has been told of delays */ private boolean takingLongTime;
/** true to stop rendering */ private boolean stopRendering;
/** the half-sizes of the window (in pixels) */ private int szHalfWidth, szHalfHeight;
/** the screen clipping */ private int screenLX, screenHX, screenLY, screenHY;
/** statistics */ private int boxCount, tinyBoxCount, lineBoxCount, lineCount, polygonCount;
/** statistics */ private int crossCount, textCount, circleCount, arcCount;
/** statistics */ private int subCellCount, tinySubCellCount;
/** the threshold of object sizes */ private float maxObjectSize;
/** the maximum cell size above which no greeking */ private float maxCellSize;
/** temporary objects (saves allocation) */ private Point tempPt1 = new Point(), tempPt2 = new Point();
/** temporary objects (saves allocation) */ private Point tempPt3 = new Point(), tempPt4 = new Point();
/** temporary object (saves allocation) */ private Rectangle tempRect = new Rectangle();
/** the color of text */ private Color textColor;
/** list of cell expansions. */ private static HashMap<Cell,VectorCellGroup> cachedCells = new HashMap<Cell,VectorCellGroup>();
/** list of polygons to include in cells */ private static HashMap<Cell,List<VectorBase>> addPolyToCell = new HashMap<Cell,List<VectorBase>>();
/** list of instances to include in cells */ private static HashMap<Cell,List<VectorSubCell>> addInstToCell = new HashMap<Cell,List<VectorSubCell>>();
/** the object that draws the rendered screen */ private static VectorDrawing topVD;
/** location for debugging icon displays */ private static int debugXP, debugYP;
/** zero rectangle */ private static final Rectangle2D CENTERRECT = new Rectangle2D.Double(0, 0, 0, 0);
private static EGraphics textGraphics = new EGraphics(false, false, null, 0, 0,0,0, 1.0,true,
new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
private static EGraphics instanceGraphics = new EGraphics(false, false, null, 0, 0,0,0, 1.0,true,
new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
private static EGraphics portGraphics = new EGraphics(false, false, null, 0, 255,0,0, 1.0,true,
new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
/**
* Class which defines the common information for all cached displayable objects
*/
private static class VectorBase
{
Layer layer;
EGraphics graphics;
boolean hideOnLowLevel;
float minSize, maxSize;
VectorBase(Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
this.layer = layer;
this.graphics = graphics;
this.hideOnLowLevel = hideOnLowLevel;
minSize = maxSize = -1;
hideOnLowLevel = false;
}
void setSize(float size1, float size2)
{
minSize = Math.min(size1, size2);
maxSize = Math.max(size1, size2);
}
}
/**
* Class which defines a cached Manhattan rectangle.
*/
private static class VectorManhattan extends VectorBase
{
float c1X, c1Y, c2X, c2Y;
int tinyColor;
VectorManhattan(float c1X, float c1Y, float c2X, float c2Y, Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.c1X = c1X;
this.c1Y = c1Y;
this.c2X = c2X;
this.c2Y = c2Y;
float dX = Math.abs(c1X - c2X);
float dY = Math.abs(c1Y - c2Y);
setSize(dX, dY);
tinyColor = -1;
if (layer != null)
{
Layer.Function fun = layer.getFunction();
if (!fun.isImplant() && !fun.isSubstrate())
{
if (graphics != null)
{
tinyColor = graphics.getColor().getRGB() & 0xFFFFFF;
}
}
}
}
}
/**
* Class which defines a cached polygon (nonmanhattan).
*/
private static class VectorPolygon extends VectorBase
{
Point2D [] points;
VectorPolygon(Point2D [] points, Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.points = points;
}
}
/**
* Class which defines a cached line.
*/
private static class VectorLine extends VectorBase
{
float fX, fY, tX, tY;
int texture;
VectorLine(double fX, double fY, double tX, double tY, int texture, Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.fX = (float)fX;
this.fY = (float)fY;
this.tX = (float)tX;
this.tY = (float)tY;
this.texture = texture;
}
}
/**
* Class which defines a cached circle (filled, opened, or thick).
*/
private static class VectorCircle extends VectorBase
{
float cX, cY, eX, eY;
int nature;
VectorCircle(double cX, double cY, double eX, double eY, int nature, Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.cX = (float)cX;
this.cY = (float)cY;
this.eX = (float)eX;
this.eY = (float)eY;
this.nature = nature;
}
}
/**
* Class which defines a cached arc of a circle (normal or thick).
*/
private static class VectorCircleArc extends VectorBase
{
float cX, cY, eX1, eY1, eX2, eY2;
boolean thick;
VectorCircleArc(double cX, double cY, double eX1, double eY1, double eX2, double eY2, boolean thick,
Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.cX = (float)cX;
this.cY = (float)cY;
this.eX1 = (float)eX1;
this.eY1 = (float)eY1;
this.eX2 = (float)eX2;
this.eY2 = (float)eY2;
this.thick = thick;
}
}
/**
* Class which defines cached text.
*/
private static class VectorText extends VectorBase
{
/** text is on a Cell */ static final int TEXTTYPECELL = 1;
/** text is on an Export */ static final int TEXTTYPEEXPORT = 2;
/** text is on a Node */ static final int TEXTTYPENODE = 3;
/** text is on an Arc */ static final int TEXTTYPEARC = 4;
/** text is on an Annotations */ static final int TEXTTYPEANNOTATION = 5;
/** text is on an Instances */ static final int TEXTTYPEINSTANCE = 6;
/** text is on an Ports */ static final int TEXTTYPEPORT = 7;
/** the text location */ Rectangle2D bounds;
/** the text style */ Poly.Type style;
/** the descriptor of the text */ TextDescriptor descript;
/** the text to draw */ String str;
/** the text height (in display units) */ float height;
/** the type of text (CELL, EXPORT, etc.) */ int textType;
/** valid for port text on a node */ NodeInst ni;
/** valid for port text or export text */ Export e;
VectorText(Rectangle2D bounds, Poly.Type style, TextDescriptor descript, String str, int textType, NodeInst ni, Export e,
boolean hideOnLowLevel, Layer layer, EGraphics graphics)
{
super(layer, graphics, hideOnLowLevel);
this.bounds = bounds;
this.style = style;
this.descript = descript;
this.str = str;
this.textType = textType;
this.ni = ni;
this.e = e;
height = 1;
if (descript != null)
{
TextDescriptor.Size tds = descript.getSize();
if (!tds.isAbsolute()) height = (float)tds.getSize();
}
}
}
/**
* Class which defines a cached cross (a dot, large or small).
*/
private static class VectorCross extends VectorBase
{
float x, y;
boolean small;
VectorCross(double x, double y, boolean small, Layer layer, EGraphics graphics, boolean hideOnLowLevel)
{
super(layer, graphics, hideOnLowLevel);
this.x = (float)x;
this.y = (float)y;
this.small = small;
}
}
/**
* Class which defines a cached subcell reference.
*/
private static class VectorSubCell
{
NodeInst ni;
Orientation pureRotate;
Cell subCell;
float offsetX, offsetY;
Point2D [] outlinePoints;
float size;
List<VectorBase> portShapes;
VectorSubCell(NodeInst ni, Point2D offset, Point2D [] outlinePoints)
{
this.ni = ni;
if (ni != null)
{
pureRotate = ni.getOrient();
subCell = (Cell)ni.getProto();
size = (float)Math.min(ni.getXSize(), ni.getYSize());
} else
{
}
if (offset == null) offsetX = offsetY = 0; else
{
offsetX = (float)offset.getX();
offsetY = (float)offset.getY();
}
this.outlinePoints = outlinePoints;
portShapes = new ArrayList<VectorBase>();
}
}
/**
* Class which holds the cell caches for a given cell.
* Since each cell is cached many times, once for every orientation on the screen,
* this object can hold many cell caches.
*/
private static class VectorCellGroup
{
Cell cell;
HashMap<String,VectorCell> orientations;
VectorCell any;
double sizeX, sizeY;
List<VectorCellExport> exports;
VectorCellGroup(Cell cell)
{
this.cell = cell;
orientations = new HashMap<String,VectorCell>();
any = null;
}
static VectorCellGroup findCellGroup(Cell cell)
{
VectorCellGroup vcg = (VectorCellGroup)cachedCells.get(cell);
if (vcg == null)
{
vcg = new VectorCellGroup(cell);
cachedCells.put(cell, vcg);
}
return vcg;
}
void clear()
{
orientations.clear();
exports.clear();
any = null;
}
VectorCell getAnyCell()
{
return any;
}
void addCell(VectorCell vc, Orientation trans)
{
String orientationName = makeOrientationName(trans);
orientations.put(orientationName, vc);
any = vc;
}
}
/**
* Class which defines the exports on a cell (used to tell if they changed)
*/
private static class VectorCellExport
{
String exportName;
Point2D exportCtr;
}
/**
* Class which defines a cached cell in a single orientation.
*/
private static class VectorCell
{
List<VectorBase> shapes;
List<VectorSubCell> subCells;
boolean hasFadeColor;
int fadeColor;
float maxFeatureSize;
boolean isParameterized;
float cellSize;
boolean fadeImage;
int fadeOffsetX, fadeOffsetY;
int [] fadeImageColors;
int fadeImageWid, fadeImageHei;
VectorCell()
{
shapes = new ArrayList<VectorBase>();
subCells = new ArrayList<VectorSubCell>();
hasFadeColor = false;
maxFeatureSize = 0;
fadeImage = false;
}
}
// ************************************* TOP LEVEL *************************************
/**
* Constructor creates a VectorDrawing object for a given EditWindow.
* @param wnd the EditWindow associated with this VectorDrawing.
*/
public VectorDrawing(EditWindow wnd)
{
this.wnd = wnd;
}
/**
* Main entry point for drawing a cell.
* @param cell the cell to draw
* @param fullInstantiate true to draw all the way to the bottom of the hierarchy.
* @param drawLimitBounds the area in the cell to display (null to show all).
*/
public void render(Cell cell, boolean fullInstantiate, Rectangle2D drawLimitBounds, VarContext context)
{
// set colors to use
textGraphics.setColor(new Color(User.getColorText()));
instanceGraphics.setColor(new Color(User.getColorInstanceOutline()));
textColor = new Color(User.getColorText() & 0xFFFFFF);
// see if any layers are being highlighted/dimmed
offscreen = wnd.getOffscreen();
offscreen.highlightingLayers = false;
for(Iterator<Layer> it = Technology.getCurrent().getLayers(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
if (layer.isDimmed())
{
offscreen.highlightingLayers = true;
break;
}
}
// set size limit
scale = (float)wnd.getScale();
maxObjectSize = (float)User.getGreekSizeLimit() / scale;
Rectangle2D screenBounds = wnd.getDisplayedBounds();
double screenArea = screenBounds.getWidth() * screenBounds.getHeight();
maxCellSize = (float)(User.getGreekCellSizeLimit() * screenArea);
// statistics
startTime = System.currentTimeMillis();
long initialUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
takingLongTime = false;
boxCount = tinyBoxCount = lineBoxCount = lineCount = polygonCount = 0;
crossCount = textCount = circleCount = arcCount = 0;
subCellCount = tinySubCellCount = 0;
// draw recursively
this.fullInstantiate = fullInstantiate;
Dimension sz = offscreen.getSize();
szHalfWidth = sz.width / 2;
szHalfHeight = sz.height / 2;
screenLX = 0; screenHX = sz.width;
screenLY = 0; screenHY = sz.height;
Point2D offset = wnd.getOffset();
offX = (float)offset.getX();
offY = (float)offset.getY();
factorX = szHalfWidth - offX*scale;
factorY = szHalfHeight + offY*scale;
if (drawLimitBounds != null)
{
Rectangle screenLimit = wnd.databaseToScreen(drawLimitBounds);
screenLX = screenLimit.x;
if (screenLX < 0) screenLX = 0;
screenHX = screenLimit.x + screenLimit.width;
if (screenHX >= sz.width) screenHX = sz.width-1;
screenLY = screenLimit.y;
if (screenLY < 0) screenLY = 0;
screenHY = screenLimit.y + screenLimit.height;
if (screenHY >= sz.height) screenHY = sz.height-1;
}
// draw the screen, starting with the top cell
stopRendering = false;
try
{
VectorCell topVC = drawCell(cell, Orientation.IDENT, context);
render(topVC, 0, 0, Orientation.IDENT, context, 0);
} catch (AbortRenderingException e)
{
}
if (takingLongTime)
{
TopLevel.setBusyCursor(false);
System.out.println("Done");
}
if (TAKE_STATS && Job.getDebug())
{
long curUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long memUsed = curUsed - initialUsed;
long renderTime = System.currentTimeMillis() - startTime;
System.out.println("Time to render: "+TextUtils.getElapsedTime(renderTime) + " Memory Used: "+ memUsed);
System.out.println(" Rendered "+boxCount+" boxes ("+tinyBoxCount+" tiny, "+lineBoxCount+" lines), "+
lineCount+" lines, "+polygonCount+" polys, "+crossCount+" crosses, "+
textCount+" texts, "+circleCount+" circles, "+arcCount+" arcs, "+
subCellCount+" subcells ("+tinySubCellCount+" tiny)");
}
}
/**
* Method to insert a manhattan rectangle into the vector cache for a Cell.
* @param lX the low X of the manhattan rectangle.
* @param lY the low Y of the manhattan rectangle.
* @param hX the high X of the manhattan rectangle.
* @param hY the high Y of the manhattan rectangle.
* @param layer the layer on which to draw the rectangle.
* @param cell the Cell in which to insert the rectangle.
*/
public static void addBoxToCell(float lX, float lY, float hX, float hY, Layer layer, Cell cell)
{
List<VectorBase> addToThisCell = addPolyToCell.get(cell);
if (addToThisCell == null)
{
addToThisCell = new ArrayList<VectorBase>();
addPolyToCell.put(cell, addToThisCell);
}
EGraphics graphics = null;
if (layer != null)
graphics = layer.getGraphics();
VectorManhattan vm = new VectorManhattan(lX, lY, hX, hY, layer, graphics, false);
addToThisCell.add(vm);
}
/**
* Method to insert a manhattan rectangle into the vector cache for a Cell.
* @param lX the low X of the manhattan rectangle.
* @param lY the low Y of the manhattan rectangle.
* @param hX the high X of the manhattan rectangle.
* @param hY the high Y of the manhattan rectangle.
* @param cell the Cell in which to insert the rectangle.
*/
public static void addInstanceToCell(float lX, float lY, float hX, float hY, Cell cell)
{
List<VectorSubCell> addToThisCell = addInstToCell.get(cell);
if (addToThisCell == null)
{
addToThisCell = new ArrayList<VectorSubCell>();
addInstToCell.put(cell, addToThisCell);
}
// store the subcell
Point2D [] points = new Point2D[4];
points[0] = new Point2D.Float(lX, lY);
points[1] = new Point2D.Float(lX, hY);
points[2] = new Point2D.Float(hX, hY);
points[3] = new Point2D.Float(hX, lY);
VectorSubCell vsc = new VectorSubCell(null, null, points);
addToThisCell.add(vsc);
}
private static final Variable.Key NCCKEY = Variable.newKey("ATTR_NCC");
/**
* Method to tell whether a Cell is parameterized.
* Code is taken from tool.drc.Quick.checkEnumerateProtos
* Could also use the code in tool.io.output.Spice.checkIfParameterized
* @param cell the Cell to examine
* @return true if the cell has parameters
*/
private boolean isCellParameterized(Cell cell)
{
for(Iterator<Variable> vIt = cell.getParameters(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
// this attribute is not a parameter
if (var.getKey() == NCCKEY) continue;
return true;
}
// for(Iterator<Variable> vIt = cell.getVariables(); vIt.hasNext(); )
// {
// Variable var = (Variable)vIt.next();
// if (var.isParam())
// {
// // this attribute is not a parameter
// if (var.getKey() == NCCKEY) continue;
// return true;
// }
// }
// look for any Java coded stuff (Logical Effort calls)
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
for(Iterator<Variable> vIt = ni.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
if (var.getCode() != TextDescriptor.Code.NONE) return true;
}
}
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
for(Iterator<Variable> vIt = ai.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
if (var.getCode() != TextDescriptor.Code.NONE) return true;
}
}
return false;
}
/**
* Class to define a signal to abort rendering.
*/
class AbortRenderingException extends Exception {}
/**
* Method called when a cell changes: removes any cached displays of that cell
* @param cell the cell that changed
*/
public static void cellChanged(Cell cell)
{
if (cell.isLinked())
{
// cell still valid: see if it changed from last cache
VectorCellGroup vcg = (VectorCellGroup)cachedCells.get(cell);
if (vcg != null && vcg.exports != null)
{
boolean changed = false;
Rectangle2D cellBounds = cell.getBounds();
if (vcg.sizeX != cellBounds.getWidth() || vcg.sizeY != cellBounds.getHeight()) changed = true; else
{
Iterator<VectorCellExport> cIt = vcg.exports.iterator();
for(Iterator<Export> it = cell.getExports(); it.hasNext(); )
{
Export e = (Export)it.next();
if (!cIt.hasNext()) { changed = true; break; }
VectorCellExport vce = (VectorCellExport)cIt.next();
if (!vce.exportName.equals(e.getName())) { changed = true; break; }
Poly poly = e.getOriginalPort().getPoly();
if (vce.exportCtr.getX() != poly.getCenterX() ||
vce.exportCtr.getY() != poly.getCenterY()) { changed = true; break; }
}
if (cIt.hasNext()) changed = true;
}
// queue parent cells for recaching if the bounds or exports changed
if (changed)
{
for(Iterator<CellUsage> it = cell.getUsagesOf(); it.hasNext(); )
{
CellUsage u = (CellUsage)it.next();
cellChanged(u.getParent());
}
}
}
}
//System.out.println("REMOVING CACHE FOR CELL "+cell);
cachedCells.remove(cell);
}
/**
* Method called when a technology's parameters change.
* All cells that use the technology must be recached.
* @param tech the technology that changed.
*/
public static void technologyChanged(Technology tech)
{
for(Iterator<Cell> it = cachedCells.keySet().iterator(); it.hasNext(); )
{
Cell cell = (Cell)it.next();
if (cell.getTechnology() != tech) continue;
VectorCellGroup vcg = (VectorCellGroup)cachedCells.get(cell);
vcg.clear();
}
}
/**
* Method called when visible layers have changed.
* Removes all "greeked images" from cached cells.
*/
public static void layerVisibilityChanged()
{
for(Iterator<Cell> it = cachedCells.keySet().iterator(); it.hasNext(); )
{
Cell cell = (Cell)it.next();
VectorCellGroup vcg = (VectorCellGroup)cachedCells.get(cell);
for(Iterator<String> oIt = vcg.orientations.keySet().iterator(); oIt.hasNext(); )
{
String orientationName = (String)oIt.next();
VectorCell vc = (VectorCell)vcg.orientations.get(orientationName);
vc.fadeImageColors = null;
vc.fadeImage = false;
}
}
}
/**
* Method to request that the current rendering be aborted because it must be restarted.
*
*/
public void abortRendering()
{
stopRendering = true;
}
/**
* Method to recursively render a cached cell.
* @param vc the cached cell to render
* @param oX the X offset for rendering the cell (in database coordinates).
* @param oY the Y offset for rendering the cell (in database coordinates).
* @param trans the orientation of the cell (this is not a transformation matrix with offsets, just an Orientation with rotation).
* @param context the VarContext for this point in the rendering.
* @param level: 0=top-level cell in window; 1=low level cell; -1=greeked cell.
*/
private void render(VectorCell vc, float oX, float oY, Orientation trans, VarContext context, int level)
throws AbortRenderingException
{
if (level == 0) topVD = this;
// render main list of shapes
drawList(oX, oY, vc.shapes, level);
// now render subcells
for(Iterator<VectorSubCell> it = vc.subCells.iterator(); it.hasNext(); )
{
if (stopRendering) throw new AbortRenderingException();
VectorSubCell vsc = (VectorSubCell)it.next();
subCellCount++;
// get instance location
float p1x = (float)vsc.outlinePoints[0].getX() + oX;
float p2x = (float)vsc.outlinePoints[1].getX() + oX;
float p3x = (float)vsc.outlinePoints[2].getX() + oX;
float p4x = (float)vsc.outlinePoints[3].getX() + oX;
float p1y = (float)vsc.outlinePoints[0].getY() + oY;
float p2y = (float)vsc.outlinePoints[1].getY() + oY;
float p3y = (float)vsc.outlinePoints[2].getY() + oY;
float p4y = (float)vsc.outlinePoints[3].getY() + oY;
databaseToScreen(p1x, p1y, tempPt1); databaseToScreen(p2x, p2y, tempPt2);
databaseToScreen(p3x, p3y, tempPt3); databaseToScreen(p4x, p4y, tempPt4);
int lX = Math.min(Math.min(tempPt1.x, tempPt2.x), Math.min(tempPt3.x, tempPt4.x));
int hX = Math.max(Math.max(tempPt1.x, tempPt2.x), Math.max(tempPt3.x, tempPt4.x));
int lY = Math.min(Math.min(tempPt1.y, tempPt2.y), Math.min(tempPt3.y, tempPt4.y));
int hY = Math.max(Math.max(tempPt1.y, tempPt2.y), Math.max(tempPt3.y, tempPt4.y));
// see if the subcell is clipped
if (hX < screenLX || lX >= screenHX) continue;
if (hY < screenLY || lY >= screenHY) continue;
// see if the cell is too tiny to draw
if (vsc.size < maxObjectSize && vsc.ni != null)
{
// VectorCellGroup vcg = VectorCellGroup.findCellGroup(vsc.subCell);
Orientation thisOrient = vsc.ni.getOrient();
Orientation recurseTrans = trans.concatenate(thisOrient);
VarContext subContext = context.push(vsc.ni);
VectorCell subVC = drawCell(vsc.subCell, recurseTrans, subContext);
makeGreekedImage(vsc, subVC);
int fadeColor = getFadeColor(subVC, subContext);
drawTinyBox(lX, hX, lY, hY, fadeColor, subVC);
tinySubCellCount++;
continue;
}
boolean expanded = false;
if (vsc.ni != null)
{
expanded = vsc.ni.isExpanded();
if (fullInstantiate) expanded = true;
}
// if not expanded, but viewing this cell in-place, expand it
if (!expanded)
{
List<NodeInst> path = wnd.getInPlaceEditNodePath();
if (path != null)
{
for(int pathIndex=0; pathIndex<path.size(); pathIndex++)
{
NodeInst niOnPath = (NodeInst)path.get(pathIndex);
if (niOnPath.getProto() == vsc.subCell)
{
expanded = true;
break;
}
}
}
}
if (expanded)
{
Orientation thisOrient = vsc.ni.getOrient();
// Orientation recurseTrans = thisOrient.concatenate(trans);
Orientation recurseTrans = trans.concatenate(thisOrient);
VarContext subContext = context.push(vsc.ni);
VectorCell subVC = drawCell(vsc.subCell, recurseTrans, subContext);
// expanded cells may be replaced with greeked versions (not icons)
if (vsc.subCell.getView() != View.ICON)
{
// may also be "tiny" if all features in the cell are tiny
if (subVC.maxFeatureSize > 0 && subVC.maxFeatureSize < maxObjectSize && subVC.cellSize < maxCellSize)
{
boolean allTinyInside = isContentsTiny(vsc.subCell, subVC, recurseTrans, context);
if (allTinyInside)
{
makeGreekedImage(vsc, subVC);
int fadeColor = getFadeColor(subVC, context);
drawTinyBox(lX, hX, lY, hY, fadeColor, subVC);
tinySubCellCount++;
continue;
}
}
// may also be "tiny" if the cell is smaller than the greeked image
if (User.isUseCellGreekingImages() && hX-lX <= MAXGREEKSIZE && hY-lY <= MAXGREEKSIZE)
{
makeGreekedImage(vsc, subVC);
int fadeColor = getFadeColor(subVC, context);
drawTinyBox(lX, hX, lY, hY, fadeColor, subVC);
tinySubCellCount++;
continue;
}
}
int subLevel = level;
if (subLevel == 0) subLevel = 1;
render(subVC, vsc.offsetX + oX, vsc.offsetY + oY, recurseTrans, subContext, subLevel);
} else
{
// now draw with the proper line type
databaseToScreen(p1x, p1y, tempPt1); databaseToScreen(p2x, p2y, tempPt2);
offscreen.drawLine(tempPt1, tempPt2, null, instanceGraphics, 0, false);
databaseToScreen(p2x, p2y, tempPt1); databaseToScreen(p3x, p3y, tempPt2);
offscreen.drawLine(tempPt1, tempPt2, null, instanceGraphics, 0, false);
databaseToScreen(p3x, p3y, tempPt1); databaseToScreen(p4x, p4y, tempPt2);
offscreen.drawLine(tempPt1, tempPt2, null, instanceGraphics, 0, false);
databaseToScreen(p1x, p1y, tempPt1); databaseToScreen(p4x, p4y, tempPt2);
offscreen.drawLine(tempPt1, tempPt2, null, instanceGraphics, 0, false);
// draw the instance name
if (User.isTextVisibilityOnInstance() && vsc.ni != null)
{
tempRect.setRect(lX, lY, hX-lX, hY-lY);
TextDescriptor descript = vsc.ni.getTextDescriptor(NodeInst.NODE_PROTO);
NodeProto np = vsc.ni.getProto();
offscreen.drawText(tempRect, Poly.Type.TEXTBOX, descript, np.describe(false), null, textGraphics, false);
}
}
drawList(oX, oY, vsc.portShapes, level);
}
}
/**
* Method to draw a list of cached shapes.
* @param oX the X offset to draw the shapes (in display coordinates).
* @param oY the Y offset to draw the shapes (in display coordinates).
* @param shapes the List of shapes (VectorBase objects).
* @param level: 0=top-level cell in window; 1=low level cell; -1=greeked cell.
*/
private void drawList(float oX, float oY, List<VectorBase> shapes, int level)
throws AbortRenderingException
{
// render all shapes
for(Iterator<VectorBase> it = shapes.iterator(); it.hasNext(); )
{
if (stopRendering) throw new AbortRenderingException();
VectorBase vb = (VectorBase)it.next();
if (vb.hideOnLowLevel && level != 0) continue;
// get visual characteristics of shape
Layer layer = vb.layer;
boolean dimmed = false;
if (layer != null)
{
if (level < 0)
{
// greeked cells ignore cut and implant layers
Layer.Function fun = layer.getFunction();
if (fun.isContact() || fun.isWell() || fun.isSubstrate()) continue;
}
// if (!forceVisible && !vb.layer.isVisible()) continue;
if (!layer.isVisible()) continue;
dimmed = layer.isDimmed();
}
// handle each shape
if (vb instanceof VectorManhattan)
{
boxCount++;
VectorManhattan vm = (VectorManhattan)vb;
if (vm.minSize < maxObjectSize)
{
int col = vm.tinyColor;
if (col < 0) continue;
if (vm.maxSize < maxObjectSize)
{
// both dimensions tiny: just draw a dot
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
int x = tempPt1.x;
int y = tempPt1.y;
if (x < screenLX || x >= screenHX) continue;
if (y < screenLY || y >= screenHY) continue;
offscreen.drawPoint(x, y, null, col);
tinyBoxCount++;
} else
{
// one dimension tiny: draw a line
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
drawTinyBox(lX, hX, lY, hY, col, null);
lineBoxCount++;
}
continue;
}
// determine coordinates of rectangle on the screen
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
// reject if completely off the screen
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
// clip to screen
if (lX < screenLX) lX = screenLX;
if (hX >= screenHX) hX = screenHX-1;
if (lY < screenLY) lY = screenLY;
if (hY >= screenHY) hY = screenHY-1;
// draw the box
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
offscreen.drawBox(lX, hX, lY, hY, layerBitMap, graphics, dimmed);
continue;
}
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
if (vb instanceof VectorLine)
{
lineCount++;
VectorLine vl = (VectorLine)vb;
// determine coordinates of line on the screen
databaseToScreen(vl.fX+oX, vl.fY+oY, tempPt1);
databaseToScreen(vl.tX+oX, vl.tY+oY, tempPt2);
// clip and draw the line
offscreen.drawLine(tempPt1, tempPt2, layerBitMap, graphics, vl.texture, dimmed);
} else if (vb instanceof VectorPolygon)
{
polygonCount++;
VectorPolygon vp = (VectorPolygon)vb;
Point [] intPoints = new Point[vp.points.length];
for(int i=0; i<vp.points.length; i++)
{
intPoints[i] = new Point();
databaseToScreen(vp.points[i].getX()+oX, vp.points[i].getY()+oY, intPoints[i]);
}
Point [] clippedPoints = GenMath.clipPoly(intPoints, screenLX, screenHX-1, screenLY, screenHY-1);
offscreen.drawPolygon(clippedPoints, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCross)
{
crossCount++;
VectorCross vcr = (VectorCross)vb;
databaseToScreen(vcr.x+oX, vcr.y+oY, tempPt1);
int size = 5;
if (vcr.small) size = 3;
offscreen.drawLine(new Point(tempPt1.x-size, tempPt1.y), new Point(tempPt1.x+size, tempPt1.y), null, graphics, 0, dimmed);
offscreen.drawLine(new Point(tempPt1.x, tempPt1.y-size), new Point(tempPt1.x, tempPt1.y+size), null, graphics, 0, dimmed);
} else if (vb instanceof VectorText)
{
VectorText vt = (VectorText)vb;
switch (vt.textType)
{
case VectorText.TEXTTYPEARC:
if (!User.isTextVisibilityOnArc()) continue;
break;
case VectorText.TEXTTYPENODE:
if (!User.isTextVisibilityOnNode()) continue;
break;
case VectorText.TEXTTYPECELL:
if (!User.isTextVisibilityOnCell()) continue;
break;
case VectorText.TEXTTYPEEXPORT:
if (!User.isTextVisibilityOnExport()) continue;
break;
case VectorText.TEXTTYPEANNOTATION:
if (!User.isTextVisibilityOnAnnotation()) continue;
break;
case VectorText.TEXTTYPEINSTANCE:
if (!User.isTextVisibilityOnInstance()) continue;
break;
case VectorText.TEXTTYPEPORT:
if (!User.isTextVisibilityOnPort()) continue;
break;
}
- if (vt.height < maxObjectSize) continue;
+ if (vt.height*User.getGlobalTextScale() < maxObjectSize) continue;
String drawString = vt.str;
databaseToScreen(vt.bounds.getMinX()+oX, vt.bounds.getMinY()+oY, tempPt1);
databaseToScreen(vt.bounds.getMaxX()+oX, vt.bounds.getMaxY()+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
// for ports, switch between the different port display methods
if (vt.textType == VectorText.TEXTTYPEPORT)
{
int portDisplayLevel = User.getPortDisplayLevel();
Color portColor = vt.e.getBasePort().getPortColor();
if (vt.ni.isExpanded()) portColor = textColor;
if (portColor != null) portGraphics.setColor(portColor);
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
if (portDisplayLevel == 2)
{
// draw port as a cross
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, portGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, portGraphics, 0, false);
crossCount++;
continue;
}
// draw port as text
if (portDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = portGraphics;
layerBitMap = null;
lX = hX = cX;
lY = hY = cY;
} else if (vt.textType == VectorText.TEXTTYPEEXPORT && vt.e != null)
{
int exportDisplayLevel = User.getExportDisplayLevel();
if (exportDisplayLevel == 2)
{
// draw export as a cross
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, textGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, textGraphics, 0, false);
crossCount++;
continue;
}
// draw export as text
if (exportDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = textGraphics;
layerBitMap = null;
}
textCount++;
tempRect.setRect(lX, lY, hX-lX, hY-lY);
offscreen.drawText(tempRect, vt.style, vt.descript, drawString, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCircle)
{
circleCount++;
VectorCircle vci = (VectorCircle)vb;
databaseToScreen(vci.cX+oX, vci.cY+oY, tempPt1);
databaseToScreen(vci.eX+oX, vci.eY+oY, tempPt2);
switch (vci.nature)
{
case 0: offscreen.drawCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 1: offscreen.drawThickCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 2: offscreen.drawDisc(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
}
} else if (vb instanceof VectorCircleArc)
{
arcCount++;
VectorCircleArc vca = (VectorCircleArc)vb;
databaseToScreen(vca.cX+oX, vca.cY+oY, tempPt1);
databaseToScreen(vca.eX1+oX, vca.eY1+oY, tempPt2);
databaseToScreen(vca.eX2+oX, vca.eY2+oY, tempPt3);
offscreen.drawCircleArc(tempPt1, tempPt2, tempPt3, vca.thick, layerBitMap, graphics, dimmed);
}
}
}
/**
* Method to convert a database coordinate to screen coordinates.
* @param dbX the X coordinate (in database units).
* @param dbY the Y coordinate (in database units).
* @param result the Point in which to store the screen coordinates.
*/
public void databaseToScreen(double dbX, double dbY, Point result)
{
double scrX = dbX * scale + factorX;
double scrY = factorY - dbY * scale;
result.x = (int)(scrX >= 0 ? scrX + 0.5 : scrX - 0.5);
result.y = (int)(scrY >= 0 ? scrY + 0.5 : scrY - 0.5);
}
/**
* Method to draw a tiny box on the screen in a given color.
* Done when the object is too small to draw in full detail.
* @param lX the low X coordinate of the box.
* @param hX the high X coordinate of the box.
* @param lY the low Y coordinate of the box.
* @param hY the high Y coordinate of the box.
* @param col the color to draw.
*/
private void drawTinyBox(int lX, int hX, int lY, int hY, int col, VectorCell greekedCell)
{
if (lX < screenLX) lX = screenLX;
if (hX >= screenHX) hX = screenHX-1;
if (lY < screenLY) lY = screenLY;
if (hY >= screenHY) hY = screenHY-1;
if (User.isUseCellGreekingImages())
{
if (greekedCell != null && greekedCell.fadeImageColors != null)
{
int backgroundColor = User.getColorBackground();
int backgroundRed = (backgroundColor >> 16) & 0xFF;
int backgroundGreen = (backgroundColor >> 8) & 0xFF;
int backgroundBlue = backgroundColor & 0xFF;
// render the icon properly with scale
int greekWid = greekedCell.fadeImageWid;
int greekHei = greekedCell.fadeImageHei;
int wid = hX - lX;
int hei = hY - lY;
float xInc = greekWid / (float)wid;
float yInc = greekHei / (float)hei;
float yPos = 0;
for(int y=0; y<hei; y++)
{
float yEndPos = yPos + yInc;
int yS = (int)yPos;
int yE = (int)yEndPos;
float xPos = 0;
for(int x=0; x<wid; x++)
{
float xEndPos = xPos + xInc;
int xS = (int)xPos;
int xE = (int)xEndPos;
float r = 0, g = 0, b = 0;
float totalArea = 0;
for(int yGrab = yS; yGrab <= yE; yGrab++)
{
if (yGrab >= greekHei) continue;
float yArea = 1;
if (yGrab == yS) yArea = (1 - (yPos - yS));
if (yGrab == yE) yArea *= (yEndPos-yE);
for(int xGrab = xS; xGrab <= xE; xGrab++)
{
if (xGrab >= greekWid) continue;
int value = greekedCell.fadeImageColors[xGrab + yGrab*greekedCell.fadeImageWid];
int red = (value >> 16) & 0xFF;
int green = (value >> 8) & 0xFF;
int blue = value & 0xFF;
float area = yArea;
if (xGrab == xS) area *= (1 - (xPos - xS));
if (xGrab == xE) area *= (xEndPos-xE);
if (area <= 0) continue;
r += red * area;
g += green * area;
b += blue * area;
totalArea += area;
}
}
if (totalArea > 0)
{
int red = (int)(r / totalArea);
if (red > 255) red = 255;
int green = (int)(g / totalArea);
if (green > 255) green = 255;
int blue = (int)(b / totalArea);
if (blue > 255) blue = 255;
if (Math.abs(backgroundRed-red) > 2 || Math.abs(backgroundGreen-green) > 2 ||
Math.abs(backgroundBlue-blue) > 2)
{
offscreen.drawPoint(lX+x, lY+y, null, (red << 16) | (green << 8) | blue);
}
}
xPos = xEndPos;
}
yPos = yEndPos;
}
if (DEBUGIMAGES)
{
for(int y=0; y<greekedCell.fadeImageHei; y++)
{
for(int x=0; x<greekedCell.fadeImageWid; x++)
{
int valToSet = greekedCell.fadeImageColors[x+y*greekedCell.fadeImageWid];
topVD.offscreen.drawPoint(greekedCell.fadeOffsetX+x+1, greekedCell.fadeOffsetY+y+1, null, valToSet);
}
topVD.offscreen.drawPoint(greekedCell.fadeOffsetX, greekedCell.fadeOffsetY+y+1, null, 0);
topVD.offscreen.drawPoint(greekedCell.fadeOffsetX+greekedCell.fadeImageWid+1, greekedCell.fadeOffsetY+y+1, null, 0);
}
for(int x=0; x<greekedCell.fadeImageWid; x++)
{
topVD.offscreen.drawPoint(greekedCell.fadeOffsetX+x, greekedCell.fadeOffsetY, null, 0);
topVD.offscreen.drawPoint(greekedCell.fadeOffsetX+x, greekedCell.fadeOffsetY+greekedCell.fadeImageHei+1, null, 0);
}
}
return;
}
}
// no greeked image: just use the greeked color
for(int y=lY; y<=hY; y++)
{
for(int x=lX; x<=hX; x++)
offscreen.drawPoint(x, y, null, col);
}
}
/**
* Method to determine whether a cell has tiny contents.
* Recursively examines the cache of this and all subcells to see if the
* maximum feature sizes are all below the global threshold "maxObjectSize".
* @param cell the Cell in question.
* @param vc the cached representation of the cell.
* @param trans the Orientation of the cell.
* @return true if the cell has all tiny contents.
*/
private boolean isContentsTiny(Cell cell, VectorCell vc, Orientation trans, VarContext context)
throws AbortRenderingException
{
if (vc.maxFeatureSize > maxObjectSize) return false;
boolean isAllTiny = true;
for(Iterator<VectorSubCell> it = vc.subCells.iterator(); it.hasNext(); )
{
VectorSubCell vsc = (VectorSubCell)it.next();
NodeInst ni = vsc.ni;
boolean expanded = ni.isExpanded();
if (fullInstantiate) expanded = true;
if (expanded)
{
Orientation thisOrient = ni.getOrient();
Orientation recurseTrans = thisOrient.concatenate(trans);
VarContext subContext = context.push(ni);
VectorCell subVC = drawCell(vsc.subCell, recurseTrans, subContext);
boolean subCellTiny = isContentsTiny(vsc.subCell, subVC, recurseTrans, subContext);
if (!subCellTiny) return false;
continue;
}
if (vsc.size > maxObjectSize) return false;
}
return true;
}
private void makeGreekedImage(VectorSubCell vsc, VectorCell subVC)
throws AbortRenderingException
{
if (subVC.fadeImage) return;
if (!User.isUseCellGreekingImages()) return;
// determine size and scale of greeked cell image
Rectangle2D cellBounds = vsc.subCell.getBounds();
Rectangle2D ownBounds = new Rectangle2D.Double(cellBounds.getMinX(), cellBounds.getMinY(), cellBounds.getWidth(), cellBounds.getHeight());
AffineTransform trans = vsc.pureRotate.rotateAbout(0, 0);
GenMath.transformRect(ownBounds, trans);
double greekScale = MAXGREEKSIZE / ownBounds.getHeight();
if (ownBounds.getWidth() > ownBounds.getHeight())
greekScale = MAXGREEKSIZE / ownBounds.getWidth();
int greekWid = (int)(ownBounds.getWidth()*greekScale + 0.5);
if (greekWid <= 0) greekWid = 1;
int greekHei = (int)(ownBounds.getHeight()*greekScale + 0.5);
if (greekHei <= 0) greekHei = 1;
// construct the offscreen buffers for the greeked cell image
EditWindow fadeWnd = EditWindow.CreateElectricDoc(vsc.subCell, null, null);
fadeWnd.setScreenSize(new Dimension(greekWid, greekHei));
fadeWnd.setScale(greekScale);
Point2D cellCtr = new Point2D.Double(ownBounds.getCenterX(), ownBounds.getCenterY());
fadeWnd.setOffset(cellCtr);
VectorDrawing subVD = new VectorDrawing(fadeWnd);
subVC.fadeOffsetX = debugXP;
subVC.fadeOffsetY = debugYP;
debugXP += MAXGREEKSIZE + 5;
if (topVD != null)
{
if (debugXP + MAXGREEKSIZE+2 >= topVD.offscreen.getSize().width)
{
debugXP = 0;
debugYP += MAXGREEKSIZE + 5;
}
}
//System.out.println("Making greek for "+vsc.subCell+" "+greekWid+"x"+greekHei);
// set rendering information for the greeked cell image
subVD.offscreen = fadeWnd.getOffscreen();
subVD.screenLX = 0; subVD.screenHX = greekWid;
subVD.screenLY = 0; subVD.screenHY = greekHei;
subVD.szHalfWidth = greekWid / 2;
subVD.szHalfHeight = greekHei / 2;
subVD.maxObjectSize = 0;
subVD.scale = (float)greekScale;
subVD.offX = (float)cellCtr.getX();
subVD.offY = (float)cellCtr.getY();
subVD.factorX = subVD.szHalfWidth - subVD.offX*subVD.scale;
subVD.factorY = subVD.szHalfHeight + subVD.offY*subVD.scale;
subVD.fullInstantiate = true;
subVD.takingLongTime = true;
// render the greeked cell
subVD.offscreen.clearImage(false, null);
subVD.render(subVC, 0, 0, vsc.pureRotate, VarContext.globalContext, -1);
subVD.offscreen.composite(null);
// remember the greeked cell image
BufferedImage img = subVD.offscreen.getBufferedImage();
subVC.fadeImageWid = img.getWidth();
subVC.fadeImageHei = img.getHeight();
subVC.fadeImageColors = new int[subVC.fadeImageWid * subVC.fadeImageHei];
int i = 0;
for(int y=0; y<subVC.fadeImageHei; y++)
{
for(int x=0; x<subVC.fadeImageWid; x++)
{
int value = img.getRGB(x, y);
subVC.fadeImageColors[i++] = value & 0xFFFFFF;
}
}
subVD.wnd.finished();
subVC.fadeImage = true;
}
/**
* Method to determine the "fade" color for a cached cell.
* Fading is done when the cell is too tiny to draw (or all of its contents are too tiny).
* Instead of drawing the cell contents, the entire cell is painted with the "fade" color.
* @param vc the cached cell.
* @return the fade color (an integer with red/green/blue).
*/
private int getFadeColor(VectorCell vc, VarContext context)
throws AbortRenderingException
{
if (vc.hasFadeColor) return vc.fadeColor;
// examine all shapes
HashMap<Layer,MutableDouble> layerAreas = new HashMap<Layer,MutableDouble>();
gatherContents(vc, layerAreas, context);
// now compute the color
Set<Layer> keys = layerAreas.keySet();
double totalArea = 0;
for(Iterator<Layer> it = keys.iterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
MutableDouble md = (MutableDouble)layerAreas.get(layer);
totalArea += md.doubleValue();
}
double r = 0, g = 0, b = 0;
if (totalArea != 0)
{
for(Iterator<Layer> it = keys.iterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
MutableDouble md = (MutableDouble)layerAreas.get(layer);
double portion = md.doubleValue() / totalArea;
EGraphics desc = layer.getGraphics();
Color col = desc.getColor();
r += col.getRed() * portion;
g += col.getGreen() * portion;
b += col.getBlue() * portion;
}
}
if (r < 0) r = 0; if (r > 255) r = 255;
if (g < 0) g = 0; if (g > 255) g = 255;
if (b < 0) b = 0; if (b > 255) b = 255;
vc.fadeColor = (((int)r) << 16) | (((int)g) << 8) | (int)b;
vc.hasFadeColor = true;
return vc.fadeColor;
}
/**
* Helper method to recursively examine a cached cell and its subcells and compute
* the coverage of each layer.
* @param vc the cached cell to examine.
* @param layerAreas a HashMap of all layers and the areas they cover.
*/
private void gatherContents(VectorCell vc, HashMap<Layer,MutableDouble> layerAreas, VarContext context)
throws AbortRenderingException
{
for(Iterator<VectorBase> it = vc.shapes.iterator(); it.hasNext(); )
{
VectorBase vb = (VectorBase)it.next();
if (vb.hideOnLowLevel) continue;
Layer layer = vb.layer;
if (layer == null) continue;
Layer.Function fun = layer.getFunction();
if (fun.isImplant() || fun.isSubstrate()) continue;
// handle each shape
double area = 0;
if (vb instanceof VectorManhattan)
{
VectorManhattan vm = (VectorManhattan)vb;
area = Math.abs((vm.c1X-vm.c2X) * (vm.c1Y-vm.c2Y));
} else if (vb instanceof VectorLine)
{
VectorLine vl = (VectorLine)vb;
area = new Point2D.Double(vl.fX, vl.fY).distance(new Point2D.Double(vl.tX, vl.tY));
} else if (vb instanceof VectorPolygon)
{
VectorPolygon vp = (VectorPolygon)vb;
area = GenMath.getAreaOfPoints(vp.points);
} else if (vb instanceof VectorCircle)
{
VectorCircle vci = (VectorCircle)vb;
double radius = new Point2D.Double(vci.cX, vci.cY).distance(new Point2D.Double(vci.eX, vci.eY));
area = radius * radius * Math.PI;
}
if (area == 0) continue;
MutableDouble md = (MutableDouble)layerAreas.get(layer);
if (md == null)
{
md = new MutableDouble(0);
layerAreas.put(layer, md);
}
md.setValue(md.doubleValue() + area);
}
for(Iterator<VectorSubCell> it = vc.subCells.iterator(); it.hasNext(); )
{
VectorSubCell vsc = (VectorSubCell)it.next();
VectorCellGroup vcg = VectorCellGroup.findCellGroup(vsc.subCell);
VectorCell subVC = vcg.getAnyCell();
VarContext subContext = context.push(vsc.ni);
if (subVC == null)
subVC = drawCell(vsc.subCell, Orientation.IDENT, subContext);
gatherContents(subVC, layerAreas, subContext);
}
}
// ************************************* CACHE CREATION *************************************
/**
* Method to cache the contents of a cell.
* @param cell the Cell to cache
* @param prevTrans the orientation of the cell (just a rotation, no offsets here).
* @return a cached cell object for the given Cell.
*/
private VectorCell drawCell(Cell cell, Orientation prevTrans, VarContext context)
throws AbortRenderingException
{
// see if this cell's vectors are cached
VectorCellGroup vcg = VectorCellGroup.findCellGroup(cell);
String orientationName = makeOrientationName(prevTrans);
VectorCell vc = (VectorCell)vcg.orientations.get(orientationName);
// if the cell is parameterized, mark it for recaching
if (vc != null && vc.isParameterized) vc = null;
// if the cell is cached, stop now
if (vc != null) return vc;
// caching the cell: check for abort and delay reporting
if (stopRendering) throw new AbortRenderingException();
if (!takingLongTime)
{
long currentTime = System.currentTimeMillis();
if (currentTime - startTime > 1000)
{
System.out.print("Display caching, please wait...");
TopLevel.setBusyCursor(true);
takingLongTime = true;
}
}
// make a new cache of the cell
vc = new VectorCell();
vcg.addCell(vc, prevTrans);
vc.isParameterized = isCellParameterized(cell);
Rectangle2D cellBounds = cell.getBounds();
vc.cellSize = (float)(cellBounds.getWidth() * cellBounds.getHeight());
AffineTransform trans = prevTrans.pureRotate();
// save size and export centers to detect hierarchical changes later
if (vcg.exports == null)
{
vcg.exports = new ArrayList<VectorCellExport>();
vcg.sizeX = cellBounds.getWidth();
vcg.sizeY = cellBounds.getHeight();
for(Iterator<Export> it = cell.getExports(); it.hasNext(); )
{
Export e = (Export)it.next();
VectorCellExport vce = new VectorCellExport();
vce.exportName = e.getName();
Poly poly = e.getOriginalPort().getPoly();
vce.exportCtr = new Point2D.Double(poly.getCenterX(), poly.getCenterY());
vcg.exports.add(vce);
}
}
//System.out.println("CACHING CELL "+cell +" WITH ORIENTATION "+orientationName);
// draw all arcs
for(Iterator<ArcInst> arcs = cell.getArcs(); arcs.hasNext(); )
{
ArcInst ai = (ArcInst)arcs.next();
drawArc(ai, trans, vc);
}
// draw all nodes
for(Iterator<NodeInst> nodes = cell.getNodes(); nodes.hasNext(); )
{
NodeInst ni = (NodeInst)nodes.next();
drawNode(ni, trans, context, vc);
}
// for schematics, sort the polygons by layer so that busses are drawn first
if (cell.getView() == View.SCHEMATIC)
{
Collections.sort(vc.shapes, new ShapeByLayer());
}
// show cell variables
int numPolys = cell.numDisplayableVariables(true);
Poly [] polys = new Poly[numPolys];
cell.addDisplayableVariables(CENTERRECT, polys, 0, wnd, true);
drawPolys(polys, DBMath.MATID, vc, true, VectorText.TEXTTYPECELL, false);
// add in anything "snuck" onto the cell
List<VectorBase> addThesePolys = addPolyToCell.get(cell);
if (addThesePolys != null)
{
for(Iterator<VectorBase> it = addThesePolys.iterator(); it.hasNext(); )
{
VectorBase vb = it.next();
vc.shapes.add(vb);
}
}
List<VectorSubCell> addTheseInsts = addInstToCell.get(cell);
if (addTheseInsts != null)
{
for(Iterator<VectorSubCell> it = addTheseInsts.iterator(); it.hasNext(); )
{
VectorSubCell vsc = it.next();
vc.subCells.add(vsc);
}
}
// icon cells should not get greeked because of their contents
if (cell.getView() == View.ICON) vc.maxFeatureSize = 0;
return vc;
}
/**
* Comparator class for sorting VectorBase objects by their layer depth.
*/
public static class ShapeByLayer implements Comparator<VectorBase>
{
/**
* Method to sort Objects by their string name.
*/
/*5*/ public int compare(VectorBase vb1, VectorBase vb2)
//4*/ public int compare(Object o1, Object o2)
{
//4*/ VectorBase vb1 = (VectorBase)o1;
//4*/ VectorBase vb2 = (VectorBase)o2;
int level1 = 1000, level2 = 1000;
if (vb1.layer != null) level1 = vb1.layer.getFunction().getLevel();
if (vb2.layer != null) level2 = vb2.layer.getFunction().getLevel();
return level1 - level2;
}
}
/**
* Method to cache a NodeInst.
* @param ni the NodeInst to cache.
* @param trans the transformation of the NodeInst to the parent Cell.
* @param vc the cached cell in which to place the NodeInst.
*/
public void drawNode(NodeInst ni, AffineTransform trans, VarContext context, VectorCell vc)
{
NodeProto np = ni.getProto();
AffineTransform localTrans = ni.rotateOut(trans);
boolean hideOnLowLevel = false;
if (ni.isVisInside() || np == Generic.tech.cellCenterNode)
hideOnLowLevel = true;
// draw the node
if (np instanceof Cell)
{
// cell instance
Cell subCell = (Cell)np;
// compute the outline
AffineTransform outlineTrans = ni.translateOut(localTrans);
Rectangle2D cellBounds = subCell.getBounds();
Poly outlinePoly = new Poly(cellBounds);
outlinePoly.transform(outlineTrans);
// record a call to the instance
Point2D ctrShift = new Point2D.Double(ni.getAnchorCenterX(), ni.getAnchorCenterY());
localTrans.transform(ctrShift, ctrShift);
VectorSubCell vsc = new VectorSubCell(ni, ctrShift, outlinePoly.getPoints());
vc.subCells.add(vsc);
showCellPorts(ni, vc, vsc, localTrans);
// draw any displayable variables on the instance
int numPolys = ni.numDisplayableVariables(true);
Poly [] polys = new Poly[numPolys];
Rectangle2D rect = ni.getUntransformedBounds();
ni.addDisplayableVariables(rect, polys, 0, wnd, true);
drawPolys(polys, localTrans, vc, false, VectorText.TEXTTYPENODE, false);
} else
{
// primitive: save it
PrimitiveNode prim = (PrimitiveNode)np;
int textType = VectorText.TEXTTYPENODE;
if (prim == Generic.tech.invisiblePinNode) textType = VectorText.TEXTTYPEANNOTATION;
Technology tech = prim.getTechnology();
Poly [] polys = tech.getShapeOfNode(ni, wnd, context, false, false, null);
boolean pureLayer = (ni.getFunction() == PrimitiveNode.Function.NODE);
drawPolys(polys, localTrans, vc, hideOnLowLevel, textType, pureLayer);
}
// draw any exports from the node
Iterator<Export> it = ni.getExports();
while (it.hasNext())
{
Export e = (Export)it.next();
Poly poly = e.getNamePoly();
Rectangle2D rect = (Rectangle2D)poly.getBounds2D().clone();
TextDescriptor descript = poly.getTextDescriptor();
Poly.Type style = descript.getPos().getPolyType();
style = Poly.rotateType(style, ni);
VectorText vt = new VectorText(poly.getBounds2D(), style, descript, null, VectorText.TEXTTYPEEXPORT, null, e,
true, null, null);
vc.shapes.add(vt);
// draw variables on the export
int numPolys = e.numDisplayableVariables(true);
if (numPolys > 0)
{
Poly [] polys = new Poly[numPolys];
e.addDisplayableVariables(rect, polys, 0, wnd, true);
drawPolys(polys, trans, vc, true, VectorText.TEXTTYPEEXPORT, false);
// drawPolys(polys, localTrans, vc, true, VectorText.TEXTTYPEEXPORT, false);
}
}
}
/**
* Method to cache an ArcInst.
* @param ai the ArcInst to cache.
* @param trans the transformation of the ArcInst to the parent cell.
* @param vc the cached cell in which to place the ArcInst.
*/
public void drawArc(ArcInst ai, AffineTransform trans, VectorCell vc)
{
// if the arc is tiny, just approximate it with a single dot
Rectangle2D arcBounds = ai.getBounds();
// see if the arc is completely clipped from the screen
Rectangle2D dbBounds = new Rectangle2D.Double(arcBounds.getX(), arcBounds.getY(), arcBounds.getWidth(), arcBounds.getHeight());
Poly p = new Poly(dbBounds);
p.transform(trans);
dbBounds = p.getBounds2D();
// draw the arc
ArcProto ap = ai.getProto();
Technology tech = ap.getTechnology();
Poly [] polys = tech.getShapeOfArc(ai, wnd);
drawPolys(polys, trans, vc, false, VectorText.TEXTTYPEARC, false);
}
/**
* Method to cache the exports on a NodeInst.
* @param ni the NodeInst with exports
* @param col the color to use.
* @param vc the cached cell in which to place the information.
* @param vsc the cached subcell reference that defines the NodeInst.
* @param localTrans the transformation of the port locations.
*/
private void showCellPorts(NodeInst ni, VectorCell vc, VectorSubCell vsc, AffineTransform localTrans)
{
// show the ports that are not further exported or connected
int numPorts = ni.getProto().getNumPorts();
boolean[] shownPorts = new boolean[numPorts];
for(Iterator<Connection> it = ni.getConnections(); it.hasNext();)
{
Connection con = (Connection) it.next();
PortInst pi = con.getPortInst();
shownPorts[pi.getPortIndex()] = true;
}
for(Iterator<Export> it = ni.getExports(); it.hasNext();)
{
Export exp = (Export) it.next();
PortInst pi = exp.getOriginalPort();
shownPorts[pi.getPortIndex()] = true;
}
// because "getShapeOfPort" includes the local rotation, it must be undone
AffineTransform thisTrans = ni.rotateIn();
for(int i = 0; i < numPorts; i++)
{
if (shownPorts[i]) continue;
Export pp = (Export)ni.getProto().getPort(i);
Poly portPoly = ni.getShapeOfPort(pp);
if (portPoly == null) continue;
// undo local rotation and add total transformation instead
portPoly.transform(thisTrans);
portPoly.transform(localTrans);
TextDescriptor descript = portPoly.getTextDescriptor();
MutableTextDescriptor portDescript = pp.getMutableTextDescriptor(Export.EXPORT_NAME);
Poly.Type style = Poly.Type.FILLED;
if (descript != null)
{
portDescript.setColorIndex(descript.getColorIndex());
style = descript.getPos().getPolyType();
}
Rectangle rect = new Rectangle(tempPt1);
VectorText vt = new VectorText(portPoly.getBounds2D(), style, descript, null, VectorText.TEXTTYPEPORT, ni, pp,
false, null, null);
vsc.portShapes.add(vt);
}
}
/**
* Method to cache an array of polygons.
* @param polys the array of polygons to cache.
* @param trans the transformation to apply to each polygon.
* @param vc the cached cell in which to place the polygons.
* @param hideOnLowLevel true if the polygons should be marked such that they are not visible on lower levels of hierarchy.
* @param pureLayer true if these polygons come from a pure layer node.
*/
private void drawPolys(Poly[] polys, AffineTransform trans, VectorCell vc, boolean hideOnLowLevel, int textType, boolean pureLayer)
{
if (polys == null) return;
for(int i = 0; i < polys.length; i++)
{
// get the polygon and transform it
Poly poly = polys[i];
if (poly == null) continue;
// transform the bounds
poly.transform(trans);
// render the polygon
renderPoly(poly, vc, hideOnLowLevel, textType, pureLayer);
}
}
/**
* Method to cache a Poly.
* @param poly the polygon to cache.
* @param vc the cached cell in which to place the polygon.
* @param hideOnLowLevel true if the polygon should be marked such that it is not visible on lower levels of hierarchy.
* @param pureLayer true if the polygon comes from a pure layer node.
*/
private void renderPoly(Poly poly, VectorCell vc, boolean hideOnLowLevel, int textType, boolean pureLayer)
{
// now draw it
Point2D [] points = poly.getPoints();
Layer layer = poly.getLayer();
EGraphics graphics = null;
if (layer != null)
graphics = layer.getGraphics();
Poly.Type style = poly.getStyle();
if (style == Poly.Type.FILLED)
{
Rectangle2D bounds = poly.getBox();
if (bounds != null)
{
// convert coordinates
float lX = (float)bounds.getMinX();
float hX = (float)bounds.getMaxX();
float lY = (float)bounds.getMinY();
float hY = (float)bounds.getMaxY();
VectorManhattan vm = new VectorManhattan(lX, lY, hX, hY, layer, graphics, hideOnLowLevel);
if (layer != null)
{
Layer.Function fun = layer.getFunction();
if (!pureLayer && (fun.isImplant() || fun.isSubstrate()))
{
float dX = hX - lX;
float dY = hY - lY;
// well and substrate layers are made smaller so that they "greek" sooner
vm.setSize(dX / 10, dY / 10);
// vm.setSize(dX / 2, dY / 2);
// this.size = (float)Math.min(ni.getXSize(), ni.getYSize());
}
}
vm.hideOnLowLevel = hideOnLowLevel;
vc.shapes.add(vm);
vc.maxFeatureSize = Math.max(vc.maxFeatureSize, vm.minSize);
return;
}
VectorPolygon vp = new VectorPolygon(points, layer, graphics, hideOnLowLevel);
vc.shapes.add(vp);
return;
}
if (style == Poly.Type.CROSSED)
{
VectorLine vl1 = new VectorLine(points[0].getX(), points[0].getY(),
points[1].getX(), points[1].getY(), 0, layer, graphics, hideOnLowLevel);
VectorLine vl2 = new VectorLine(points[1].getX(), points[1].getY(),
points[2].getX(), points[2].getY(), 0, layer, graphics, hideOnLowLevel);
VectorLine vl3 = new VectorLine(points[2].getX(), points[2].getY(),
points[3].getX(), points[3].getY(), 0, layer, graphics, hideOnLowLevel);
VectorLine vl4 = new VectorLine(points[3].getX(), points[3].getY(),
points[0].getX(), points[0].getY(), 0, layer, graphics, hideOnLowLevel);
VectorLine vl5 = new VectorLine(points[0].getX(), points[0].getY(),
points[2].getX(), points[2].getY(), 0, layer, graphics, hideOnLowLevel);
VectorLine vl6 = new VectorLine(points[1].getX(), points[1].getY(),
points[3].getX(), points[3].getY(), 0, layer, graphics, hideOnLowLevel);
vc.shapes.add(vl1);
vc.shapes.add(vl2);
vc.shapes.add(vl3);
vc.shapes.add(vl4);
vc.shapes.add(vl5);
vc.shapes.add(vl6);
return;
}
if (style.isText())
{
Rectangle2D bounds = poly.getBounds2D();
TextDescriptor descript = poly.getTextDescriptor();
String str = poly.getString();
VectorText vt = new VectorText(bounds, style, descript, str, textType, null, null,
hideOnLowLevel, layer, graphics);
vc.shapes.add(vt);
vc.maxFeatureSize = Math.max(vc.maxFeatureSize, vt.height);
return;
}
if (style == Poly.Type.CLOSED || style == Poly.Type.OPENED || style == Poly.Type.OPENEDT1 ||
style == Poly.Type.OPENEDT2 || style == Poly.Type.OPENEDT3)
{
int lineType = 0;
if (style == Poly.Type.OPENEDT1) lineType = 1; else
if (style == Poly.Type.OPENEDT2) lineType = 2; else
if (style == Poly.Type.OPENEDT3) lineType = 3;
for(int j=1; j<points.length; j++)
{
Point2D oldPt = points[j-1];
Point2D newPt = points[j];
VectorLine vl = new VectorLine(oldPt.getX(), oldPt.getY(),
newPt.getX(), newPt.getY(), lineType, layer, graphics, hideOnLowLevel);
vc.shapes.add(vl);
}
if (style == Poly.Type.CLOSED)
{
Point2D oldPt = points[points.length-1];
Point2D newPt = points[0];
VectorLine vl = new VectorLine(oldPt.getX(), oldPt.getY(),
newPt.getX(), newPt.getY(), lineType, layer, graphics, hideOnLowLevel);
vc.shapes.add(vl);
}
return;
}
if (style == Poly.Type.VECTORS)
{
for(int j=0; j<points.length; j+=2)
{
Point2D oldPt = points[j];
Point2D newPt = points[j+1];
VectorLine vl = new VectorLine(oldPt.getX(), oldPt.getY(),
newPt.getX(), newPt.getY(), 0, layer, graphics, hideOnLowLevel);
vc.shapes.add(vl);
}
return;
}
if (style == Poly.Type.CIRCLE)
{
VectorCircle vci = new VectorCircle(points[0].getX(), points[0].getY(),
points[1].getX(), points[1].getY(), 0, layer, graphics, hideOnLowLevel);
vc.shapes.add(vci);
return;
}
if (style == Poly.Type.THICKCIRCLE)
{
VectorCircle vci = new VectorCircle(points[0].getX(), points[0].getY(),
points[1].getX(), points[1].getY(), 1, layer, graphics, hideOnLowLevel);
vc.shapes.add(vci);
return;
}
if (style == Poly.Type.DISC)
{
VectorCircle vci = new VectorCircle(points[0].getX(), points[0].getY(), points[1].getX(),
points[1].getY(), 2, layer, graphics, hideOnLowLevel);
vc.shapes.add(vci);
return;
}
if (style == Poly.Type.CIRCLEARC || style == Poly.Type.THICKCIRCLEARC)
{
VectorCircleArc vca = new VectorCircleArc(points[0].getX(), points[0].getY(),
points[1].getX(), points[1].getY(), points[2].getX(), points[2].getY(),
style == Poly.Type.THICKCIRCLEARC, layer, graphics, hideOnLowLevel);
vc.shapes.add(vca);
return;
}
if (style == Poly.Type.CROSS)
{
// draw the cross
VectorCross vcr = new VectorCross(points[0].getX(), points[0].getY(), true, layer, graphics, hideOnLowLevel);
vc.shapes.add(vcr);
return;
}
if (style == Poly.Type.BIGCROSS)
{
// draw the big cross
VectorCross vcr = new VectorCross(points[0].getX(), points[0].getY(), false, layer, graphics, hideOnLowLevel);
vc.shapes.add(vcr);
return;
}
}
/**
* Method to construct a string that describes an orientation.
* This method is used instead of "Orientation.toString" because
* it uses the old C style method that isn't redundant.
* @param orient the orientation.
* @return a unique string describing it.
*/
private static String makeOrientationName(Orientation orient)
{
String oName = Integer.toString(orient.getCAngle());
if (orient.isCTranspose()) oName += "T";
return oName;
}
}
| true | true | private void drawList(float oX, float oY, List<VectorBase> shapes, int level)
throws AbortRenderingException
{
// render all shapes
for(Iterator<VectorBase> it = shapes.iterator(); it.hasNext(); )
{
if (stopRendering) throw new AbortRenderingException();
VectorBase vb = (VectorBase)it.next();
if (vb.hideOnLowLevel && level != 0) continue;
// get visual characteristics of shape
Layer layer = vb.layer;
boolean dimmed = false;
if (layer != null)
{
if (level < 0)
{
// greeked cells ignore cut and implant layers
Layer.Function fun = layer.getFunction();
if (fun.isContact() || fun.isWell() || fun.isSubstrate()) continue;
}
// if (!forceVisible && !vb.layer.isVisible()) continue;
if (!layer.isVisible()) continue;
dimmed = layer.isDimmed();
}
// handle each shape
if (vb instanceof VectorManhattan)
{
boxCount++;
VectorManhattan vm = (VectorManhattan)vb;
if (vm.minSize < maxObjectSize)
{
int col = vm.tinyColor;
if (col < 0) continue;
if (vm.maxSize < maxObjectSize)
{
// both dimensions tiny: just draw a dot
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
int x = tempPt1.x;
int y = tempPt1.y;
if (x < screenLX || x >= screenHX) continue;
if (y < screenLY || y >= screenHY) continue;
offscreen.drawPoint(x, y, null, col);
tinyBoxCount++;
} else
{
// one dimension tiny: draw a line
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
drawTinyBox(lX, hX, lY, hY, col, null);
lineBoxCount++;
}
continue;
}
// determine coordinates of rectangle on the screen
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
// reject if completely off the screen
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
// clip to screen
if (lX < screenLX) lX = screenLX;
if (hX >= screenHX) hX = screenHX-1;
if (lY < screenLY) lY = screenLY;
if (hY >= screenHY) hY = screenHY-1;
// draw the box
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
offscreen.drawBox(lX, hX, lY, hY, layerBitMap, graphics, dimmed);
continue;
}
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
if (vb instanceof VectorLine)
{
lineCount++;
VectorLine vl = (VectorLine)vb;
// determine coordinates of line on the screen
databaseToScreen(vl.fX+oX, vl.fY+oY, tempPt1);
databaseToScreen(vl.tX+oX, vl.tY+oY, tempPt2);
// clip and draw the line
offscreen.drawLine(tempPt1, tempPt2, layerBitMap, graphics, vl.texture, dimmed);
} else if (vb instanceof VectorPolygon)
{
polygonCount++;
VectorPolygon vp = (VectorPolygon)vb;
Point [] intPoints = new Point[vp.points.length];
for(int i=0; i<vp.points.length; i++)
{
intPoints[i] = new Point();
databaseToScreen(vp.points[i].getX()+oX, vp.points[i].getY()+oY, intPoints[i]);
}
Point [] clippedPoints = GenMath.clipPoly(intPoints, screenLX, screenHX-1, screenLY, screenHY-1);
offscreen.drawPolygon(clippedPoints, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCross)
{
crossCount++;
VectorCross vcr = (VectorCross)vb;
databaseToScreen(vcr.x+oX, vcr.y+oY, tempPt1);
int size = 5;
if (vcr.small) size = 3;
offscreen.drawLine(new Point(tempPt1.x-size, tempPt1.y), new Point(tempPt1.x+size, tempPt1.y), null, graphics, 0, dimmed);
offscreen.drawLine(new Point(tempPt1.x, tempPt1.y-size), new Point(tempPt1.x, tempPt1.y+size), null, graphics, 0, dimmed);
} else if (vb instanceof VectorText)
{
VectorText vt = (VectorText)vb;
switch (vt.textType)
{
case VectorText.TEXTTYPEARC:
if (!User.isTextVisibilityOnArc()) continue;
break;
case VectorText.TEXTTYPENODE:
if (!User.isTextVisibilityOnNode()) continue;
break;
case VectorText.TEXTTYPECELL:
if (!User.isTextVisibilityOnCell()) continue;
break;
case VectorText.TEXTTYPEEXPORT:
if (!User.isTextVisibilityOnExport()) continue;
break;
case VectorText.TEXTTYPEANNOTATION:
if (!User.isTextVisibilityOnAnnotation()) continue;
break;
case VectorText.TEXTTYPEINSTANCE:
if (!User.isTextVisibilityOnInstance()) continue;
break;
case VectorText.TEXTTYPEPORT:
if (!User.isTextVisibilityOnPort()) continue;
break;
}
if (vt.height < maxObjectSize) continue;
String drawString = vt.str;
databaseToScreen(vt.bounds.getMinX()+oX, vt.bounds.getMinY()+oY, tempPt1);
databaseToScreen(vt.bounds.getMaxX()+oX, vt.bounds.getMaxY()+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
// for ports, switch between the different port display methods
if (vt.textType == VectorText.TEXTTYPEPORT)
{
int portDisplayLevel = User.getPortDisplayLevel();
Color portColor = vt.e.getBasePort().getPortColor();
if (vt.ni.isExpanded()) portColor = textColor;
if (portColor != null) portGraphics.setColor(portColor);
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
if (portDisplayLevel == 2)
{
// draw port as a cross
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, portGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, portGraphics, 0, false);
crossCount++;
continue;
}
// draw port as text
if (portDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = portGraphics;
layerBitMap = null;
lX = hX = cX;
lY = hY = cY;
} else if (vt.textType == VectorText.TEXTTYPEEXPORT && vt.e != null)
{
int exportDisplayLevel = User.getExportDisplayLevel();
if (exportDisplayLevel == 2)
{
// draw export as a cross
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, textGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, textGraphics, 0, false);
crossCount++;
continue;
}
// draw export as text
if (exportDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = textGraphics;
layerBitMap = null;
}
textCount++;
tempRect.setRect(lX, lY, hX-lX, hY-lY);
offscreen.drawText(tempRect, vt.style, vt.descript, drawString, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCircle)
{
circleCount++;
VectorCircle vci = (VectorCircle)vb;
databaseToScreen(vci.cX+oX, vci.cY+oY, tempPt1);
databaseToScreen(vci.eX+oX, vci.eY+oY, tempPt2);
switch (vci.nature)
{
case 0: offscreen.drawCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 1: offscreen.drawThickCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 2: offscreen.drawDisc(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
}
} else if (vb instanceof VectorCircleArc)
{
arcCount++;
VectorCircleArc vca = (VectorCircleArc)vb;
databaseToScreen(vca.cX+oX, vca.cY+oY, tempPt1);
databaseToScreen(vca.eX1+oX, vca.eY1+oY, tempPt2);
databaseToScreen(vca.eX2+oX, vca.eY2+oY, tempPt3);
offscreen.drawCircleArc(tempPt1, tempPt2, tempPt3, vca.thick, layerBitMap, graphics, dimmed);
}
}
}
| private void drawList(float oX, float oY, List<VectorBase> shapes, int level)
throws AbortRenderingException
{
// render all shapes
for(Iterator<VectorBase> it = shapes.iterator(); it.hasNext(); )
{
if (stopRendering) throw new AbortRenderingException();
VectorBase vb = (VectorBase)it.next();
if (vb.hideOnLowLevel && level != 0) continue;
// get visual characteristics of shape
Layer layer = vb.layer;
boolean dimmed = false;
if (layer != null)
{
if (level < 0)
{
// greeked cells ignore cut and implant layers
Layer.Function fun = layer.getFunction();
if (fun.isContact() || fun.isWell() || fun.isSubstrate()) continue;
}
// if (!forceVisible && !vb.layer.isVisible()) continue;
if (!layer.isVisible()) continue;
dimmed = layer.isDimmed();
}
// handle each shape
if (vb instanceof VectorManhattan)
{
boxCount++;
VectorManhattan vm = (VectorManhattan)vb;
if (vm.minSize < maxObjectSize)
{
int col = vm.tinyColor;
if (col < 0) continue;
if (vm.maxSize < maxObjectSize)
{
// both dimensions tiny: just draw a dot
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
int x = tempPt1.x;
int y = tempPt1.y;
if (x < screenLX || x >= screenHX) continue;
if (y < screenLY || y >= screenHY) continue;
offscreen.drawPoint(x, y, null, col);
tinyBoxCount++;
} else
{
// one dimension tiny: draw a line
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
drawTinyBox(lX, hX, lY, hY, col, null);
lineBoxCount++;
}
continue;
}
// determine coordinates of rectangle on the screen
databaseToScreen(vm.c1X+oX, vm.c1Y+oY, tempPt1);
databaseToScreen(vm.c2X+oX, vm.c2Y+oY, tempPt2);
// reject if completely off the screen
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (hX < screenLX || lX >= screenHX) continue;
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
if (hY < screenLY || lY >= screenHY) continue;
// clip to screen
if (lX < screenLX) lX = screenLX;
if (hX >= screenHX) hX = screenHX-1;
if (lY < screenLY) lY = screenLY;
if (hY >= screenHY) hY = screenHY-1;
// draw the box
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
offscreen.drawBox(lX, hX, lY, hY, layerBitMap, graphics, dimmed);
continue;
}
byte [][] layerBitMap = null;
EGraphics graphics = vb.graphics;
if (graphics != null)
{
int layerNum = graphics.getTransparentLayer() - 1;
if (layerNum < offscreen.numLayerBitMaps) layerBitMap = offscreen.getLayerBitMap(layerNum);
}
if (vb instanceof VectorLine)
{
lineCount++;
VectorLine vl = (VectorLine)vb;
// determine coordinates of line on the screen
databaseToScreen(vl.fX+oX, vl.fY+oY, tempPt1);
databaseToScreen(vl.tX+oX, vl.tY+oY, tempPt2);
// clip and draw the line
offscreen.drawLine(tempPt1, tempPt2, layerBitMap, graphics, vl.texture, dimmed);
} else if (vb instanceof VectorPolygon)
{
polygonCount++;
VectorPolygon vp = (VectorPolygon)vb;
Point [] intPoints = new Point[vp.points.length];
for(int i=0; i<vp.points.length; i++)
{
intPoints[i] = new Point();
databaseToScreen(vp.points[i].getX()+oX, vp.points[i].getY()+oY, intPoints[i]);
}
Point [] clippedPoints = GenMath.clipPoly(intPoints, screenLX, screenHX-1, screenLY, screenHY-1);
offscreen.drawPolygon(clippedPoints, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCross)
{
crossCount++;
VectorCross vcr = (VectorCross)vb;
databaseToScreen(vcr.x+oX, vcr.y+oY, tempPt1);
int size = 5;
if (vcr.small) size = 3;
offscreen.drawLine(new Point(tempPt1.x-size, tempPt1.y), new Point(tempPt1.x+size, tempPt1.y), null, graphics, 0, dimmed);
offscreen.drawLine(new Point(tempPt1.x, tempPt1.y-size), new Point(tempPt1.x, tempPt1.y+size), null, graphics, 0, dimmed);
} else if (vb instanceof VectorText)
{
VectorText vt = (VectorText)vb;
switch (vt.textType)
{
case VectorText.TEXTTYPEARC:
if (!User.isTextVisibilityOnArc()) continue;
break;
case VectorText.TEXTTYPENODE:
if (!User.isTextVisibilityOnNode()) continue;
break;
case VectorText.TEXTTYPECELL:
if (!User.isTextVisibilityOnCell()) continue;
break;
case VectorText.TEXTTYPEEXPORT:
if (!User.isTextVisibilityOnExport()) continue;
break;
case VectorText.TEXTTYPEANNOTATION:
if (!User.isTextVisibilityOnAnnotation()) continue;
break;
case VectorText.TEXTTYPEINSTANCE:
if (!User.isTextVisibilityOnInstance()) continue;
break;
case VectorText.TEXTTYPEPORT:
if (!User.isTextVisibilityOnPort()) continue;
break;
}
if (vt.height*User.getGlobalTextScale() < maxObjectSize) continue;
String drawString = vt.str;
databaseToScreen(vt.bounds.getMinX()+oX, vt.bounds.getMinY()+oY, tempPt1);
databaseToScreen(vt.bounds.getMaxX()+oX, vt.bounds.getMaxY()+oY, tempPt2);
int lX, hX, lY, hY;
if (tempPt1.x < tempPt2.x) { lX = tempPt1.x; hX = tempPt2.x; } else
{ lX = tempPt2.x; hX = tempPt1.x; }
if (tempPt1.y < tempPt2.y) { lY = tempPt1.y; hY = tempPt2.y; } else
{ lY = tempPt2.y; hY = tempPt1.y; }
// for ports, switch between the different port display methods
if (vt.textType == VectorText.TEXTTYPEPORT)
{
int portDisplayLevel = User.getPortDisplayLevel();
Color portColor = vt.e.getBasePort().getPortColor();
if (vt.ni.isExpanded()) portColor = textColor;
if (portColor != null) portGraphics.setColor(portColor);
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
if (portDisplayLevel == 2)
{
// draw port as a cross
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, portGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, portGraphics, 0, false);
crossCount++;
continue;
}
// draw port as text
if (portDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = portGraphics;
layerBitMap = null;
lX = hX = cX;
lY = hY = cY;
} else if (vt.textType == VectorText.TEXTTYPEEXPORT && vt.e != null)
{
int exportDisplayLevel = User.getExportDisplayLevel();
if (exportDisplayLevel == 2)
{
// draw export as a cross
int cX = (lX + hX) / 2;
int cY = (lY + hY) / 2;
int size = 3;
offscreen.drawLine(new Point(cX-size, cY), new Point(cX+size, cY), null, textGraphics, 0, false);
offscreen.drawLine(new Point(cX, cY-size), new Point(cX, cY+size), null, textGraphics, 0, false);
crossCount++;
continue;
}
// draw export as text
if (exportDisplayLevel == 1) drawString = vt.e.getShortName(); else
drawString = vt.e.getName();
graphics = textGraphics;
layerBitMap = null;
}
textCount++;
tempRect.setRect(lX, lY, hX-lX, hY-lY);
offscreen.drawText(tempRect, vt.style, vt.descript, drawString, layerBitMap, graphics, dimmed);
} else if (vb instanceof VectorCircle)
{
circleCount++;
VectorCircle vci = (VectorCircle)vb;
databaseToScreen(vci.cX+oX, vci.cY+oY, tempPt1);
databaseToScreen(vci.eX+oX, vci.eY+oY, tempPt2);
switch (vci.nature)
{
case 0: offscreen.drawCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 1: offscreen.drawThickCircle(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
case 2: offscreen.drawDisc(tempPt1, tempPt2, layerBitMap, graphics, dimmed); break;
}
} else if (vb instanceof VectorCircleArc)
{
arcCount++;
VectorCircleArc vca = (VectorCircleArc)vb;
databaseToScreen(vca.cX+oX, vca.cY+oY, tempPt1);
databaseToScreen(vca.eX1+oX, vca.eY1+oY, tempPt2);
databaseToScreen(vca.eX2+oX, vca.eY2+oY, tempPt3);
offscreen.drawCircleArc(tempPt1, tempPt2, tempPt3, vca.thick, layerBitMap, graphics, dimmed);
}
}
}
|
diff --git a/tools/packworkspace/src/main/java/org/overturetool/tools/packworkspace/testing/LatexBuilder.java b/tools/packworkspace/src/main/java/org/overturetool/tools/packworkspace/testing/LatexBuilder.java
index 749d4454a6..723cbaf4aa 100644
--- a/tools/packworkspace/src/main/java/org/overturetool/tools/packworkspace/testing/LatexBuilder.java
+++ b/tools/packworkspace/src/main/java/org/overturetool/tools/packworkspace/testing/LatexBuilder.java
@@ -1,272 +1,272 @@
/*******************************************************************************
* Copyright (c) 2009, 2011 Overture Team and others.
*
* Overture 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.
*
* Overture 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 Overture. If not, see <http://www.gnu.org/licenses/>.
*
* The Overture Tool web-site: http://overturetool.org/
*******************************************************************************/
package org.overturetool.tools.packworkspace.testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;
import org.overturetool.tools.packworkspace.ProjectPacker;
import org.overturetool.tools.packworkspace.latex.FileUtils;
import org.overturetool.tools.packworkspace.testing.ProjectTester.Phase;
import org.overturetool.vdmj.runtime.Interpreter;
import org.overturetool.vdmj.runtime.LatexSourceFile;
import org.overturetool.vdmj.runtime.SourceFile;
public class LatexBuilder
{
final static String OUTPUT_FOLDER_NAME = "latex";
final String PROJECT_INCLUDE_MODEL_FILES = "%PROJECT_INCLUDE_MODEL_FILES";
final String TITLE = "%TITLE";
final String AUTHOR = "%AUTHOR";
ProjectPacker project;
List<String> includes = new Vector<String>();
File output = null;
private String documentFileName = "";
private String alternativeDocumentFileName = "";
private Process p;
private static List<Process> processes = new Vector<Process>();
private static List<ProcessConsolePrinter> processConsolePrinters = new Vector<ProcessConsolePrinter>();
public static void destroy()
{
for (Process p : LatexBuilder.processes)
{
if (p != null)
p.destroy();
}
for (Thread t : processConsolePrinters)
{
if (t != null)
t.interrupt();
}
}
public File getLatexDirectory()
{
return output;
}
public LatexBuilder(ProjectPacker project)
{
this.project = project;
}
public void build(File reportLocation, Interpreter interpreter,
String author) throws IOException
{
File projectDir = new File(reportLocation, project.getSettings().getName());
output = new File(projectDir, OUTPUT_FOLDER_NAME);
if (!output.exists())
output.mkdirs();
String languageStyleFolder = "";
String styleName = "VDM_PP";
switch (project.getDialect())
{
case VDM_PP:
languageStyleFolder = "pp";
styleName = "VDM_PP";
break;
case VDM_RT:
languageStyleFolder = "rt";
styleName = "VDM_RT";
break;
case VDM_SL:
languageStyleFolder = "sl";
styleName = "VDM_SL";
break;
}
String overturesty = FileUtils.readFile("/latex/overture.sty");
overturesty = overturesty.replace("OVERTURE_LANGUAGE", styleName);
String overturelanguagedef = FileUtils.readFile("/latex/"
+ languageStyleFolder + "/overturelanguagedef.sty");
FileUtils.writeFile(overturesty, new File(output, "/overture.sty"));
FileUtils.writeFile(overturelanguagedef, new File(output, "/overturelanguagedef.sty"));
for (File f : interpreter.getSourceFiles())
{
SourceFile sf = interpreter.getSourceFile(f);
File texFile = new File(output, sf.filename.getName() + ".tex");
addInclude(texFile.getAbsolutePath());
try
{
PrintWriter pw = new PrintWriter(texFile);
//new LatexSourceFile(sf).printCoverage(pw, false, true, true);
new LatexSourceFile(sf).print(pw, false, true, false,false);
pw.flush();
pw.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
String documentName = "";
if (alternativeDocumentFileName == null
|| alternativeDocumentFileName.length() == 0)
documentName = saveDocument(output, project.getSettings().getName(), author);
else
documentName = alternativeDocumentFileName;
- p = Runtime.getRuntime().exec("pdflatex " + documentName, null, output);
+ p = Runtime.getRuntime().exec("pdflatex -halt-on-error " + documentName, null, output);
processes.add(p);
ProcessConsolePrinter p1 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Err.txt"), p.getErrorStream());
p1.start();
ProcessConsolePrinter p2 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Out.txt"), p.getInputStream());
p2.start();
// try
// {
// p.waitFor();
// } catch (InterruptedException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// p1.interrupt();
// p2.interrupt();
}
public boolean isFinished()
{
try
{
if (p != null)
{
p.exitValue();
}
} catch (IllegalThreadStateException e)
{
return false;
}
return true;
}
public String saveDocument(File projectRoot, String name, String author)
throws IOException
{
String document = FileUtils.readFile("/latex/document.tex");
setDocumentFileName(name + ".tex");
File latexRoot = output;
StringBuilder sb = new StringBuilder();
String title = "Coverage Report: " + name;
for (String path : includes)
{
String includeName = path;
includeName = includeName.substring(0, includeName.lastIndexOf('.'));
includeName = includeName.substring(0, includeName.lastIndexOf('.'));
String tmp = includeName.replace('\\', '/');
includeName = tmp.substring(tmp.lastIndexOf('/') + 1);
sb.append("\n" + "\\section{" + latexQuote(includeName) + "}");
if (path.contains(latexRoot.getAbsolutePath()))
{
path = path.substring(latexRoot.getAbsolutePath().length());
// sb.append("\n" + "\\input{" + (".." + path).replace('\\',
// '/')
// + "}");
sb.append("\n" + "\\input{"
+ (path).replace('\\', '/').substring(1, path.length())
+ "}");
} else
sb.append("\n" + "\\input{" + path.replace('\\', '/') + "}");
}
document = document.replace(TITLE, latexQuote(title)).replace(PROJECT_INCLUDE_MODEL_FILES, sb.toString());
if (author != null && author.trim().length() != 0)
document = document.replace(AUTHOR, "\\author{"
+ latexQuote(author) + "}");
FileUtils.writeFile(document, new File(output, getDocumentFileName()));
return getDocumentFileName();
}
public boolean isBuild()
{
if (getDocumentFileName().length() > 5)
{
return new File(output, getDocumentFileName().substring(0, getDocumentFileName().length() - 4)
+ ".pdf").exists();
}
return false;
}
public File getPdfFile()
{
if (getDocumentFileName().length() > 5)
{
return new File(output, getDocumentFileName().substring(0, getDocumentFileName().length() - 4)
+ ".pdf");
}
return null;
}
public static String latexQuote(String s)
{
// Latex specials: \# \$ \% \^{} \& \_ \{ \} \~{} \\
return s.replace("\\", "\\textbackslash ").replace("#", "\\#").replace("$", "\\$").replace("%", "\\%").replace("&", "\\&").replace("_", "\\_").replace("{", "\\{").replace("}", "\\}").replace("~", "\\~").replaceAll("\\^{1}", "\\\\^{}");
}
public void addInclude(String path)
{
if (!includes.contains(path))
includes.add(path);
}
public void setDocumentFileName(String documentFileName)
{
this.documentFileName = documentFileName;
}
public String getDocumentFileName()
{
return documentFileName;
}
public void setAlternativeDocumentFileName(
String alternativeDocumentFileName)
{
this.alternativeDocumentFileName = alternativeDocumentFileName;
}
public String getAlternativeDocumentFileName()
{
return alternativeDocumentFileName;
}
}
| true | true | public void build(File reportLocation, Interpreter interpreter,
String author) throws IOException
{
File projectDir = new File(reportLocation, project.getSettings().getName());
output = new File(projectDir, OUTPUT_FOLDER_NAME);
if (!output.exists())
output.mkdirs();
String languageStyleFolder = "";
String styleName = "VDM_PP";
switch (project.getDialect())
{
case VDM_PP:
languageStyleFolder = "pp";
styleName = "VDM_PP";
break;
case VDM_RT:
languageStyleFolder = "rt";
styleName = "VDM_RT";
break;
case VDM_SL:
languageStyleFolder = "sl";
styleName = "VDM_SL";
break;
}
String overturesty = FileUtils.readFile("/latex/overture.sty");
overturesty = overturesty.replace("OVERTURE_LANGUAGE", styleName);
String overturelanguagedef = FileUtils.readFile("/latex/"
+ languageStyleFolder + "/overturelanguagedef.sty");
FileUtils.writeFile(overturesty, new File(output, "/overture.sty"));
FileUtils.writeFile(overturelanguagedef, new File(output, "/overturelanguagedef.sty"));
for (File f : interpreter.getSourceFiles())
{
SourceFile sf = interpreter.getSourceFile(f);
File texFile = new File(output, sf.filename.getName() + ".tex");
addInclude(texFile.getAbsolutePath());
try
{
PrintWriter pw = new PrintWriter(texFile);
//new LatexSourceFile(sf).printCoverage(pw, false, true, true);
new LatexSourceFile(sf).print(pw, false, true, false,false);
pw.flush();
pw.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
String documentName = "";
if (alternativeDocumentFileName == null
|| alternativeDocumentFileName.length() == 0)
documentName = saveDocument(output, project.getSettings().getName(), author);
else
documentName = alternativeDocumentFileName;
p = Runtime.getRuntime().exec("pdflatex " + documentName, null, output);
processes.add(p);
ProcessConsolePrinter p1 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Err.txt"), p.getErrorStream());
p1.start();
ProcessConsolePrinter p2 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Out.txt"), p.getInputStream());
p2.start();
// try
// {
// p.waitFor();
// } catch (InterruptedException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// p1.interrupt();
// p2.interrupt();
}
| public void build(File reportLocation, Interpreter interpreter,
String author) throws IOException
{
File projectDir = new File(reportLocation, project.getSettings().getName());
output = new File(projectDir, OUTPUT_FOLDER_NAME);
if (!output.exists())
output.mkdirs();
String languageStyleFolder = "";
String styleName = "VDM_PP";
switch (project.getDialect())
{
case VDM_PP:
languageStyleFolder = "pp";
styleName = "VDM_PP";
break;
case VDM_RT:
languageStyleFolder = "rt";
styleName = "VDM_RT";
break;
case VDM_SL:
languageStyleFolder = "sl";
styleName = "VDM_SL";
break;
}
String overturesty = FileUtils.readFile("/latex/overture.sty");
overturesty = overturesty.replace("OVERTURE_LANGUAGE", styleName);
String overturelanguagedef = FileUtils.readFile("/latex/"
+ languageStyleFolder + "/overturelanguagedef.sty");
FileUtils.writeFile(overturesty, new File(output, "/overture.sty"));
FileUtils.writeFile(overturelanguagedef, new File(output, "/overturelanguagedef.sty"));
for (File f : interpreter.getSourceFiles())
{
SourceFile sf = interpreter.getSourceFile(f);
File texFile = new File(output, sf.filename.getName() + ".tex");
addInclude(texFile.getAbsolutePath());
try
{
PrintWriter pw = new PrintWriter(texFile);
//new LatexSourceFile(sf).printCoverage(pw, false, true, true);
new LatexSourceFile(sf).print(pw, false, true, false,false);
pw.flush();
pw.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
String documentName = "";
if (alternativeDocumentFileName == null
|| alternativeDocumentFileName.length() == 0)
documentName = saveDocument(output, project.getSettings().getName(), author);
else
documentName = alternativeDocumentFileName;
p = Runtime.getRuntime().exec("pdflatex -halt-on-error " + documentName, null, output);
processes.add(p);
ProcessConsolePrinter p1 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Err.txt"), p.getErrorStream());
p1.start();
ProcessConsolePrinter p2 = new ProcessConsolePrinter(new File(output, Phase.Latex
+ "Out.txt"), p.getInputStream());
p2.start();
// try
// {
// p.waitFor();
// } catch (InterruptedException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// p1.interrupt();
// p2.interrupt();
}
|
diff --git a/membrane-esb/core/src/test/java/com/predic8/membrane/core/interceptor/rest/HTTP2XMLInterceptorTest.java b/membrane-esb/core/src/test/java/com/predic8/membrane/core/interceptor/rest/HTTP2XMLInterceptorTest.java
index 28ea0f42..0023249e 100644
--- a/membrane-esb/core/src/test/java/com/predic8/membrane/core/interceptor/rest/HTTP2XMLInterceptorTest.java
+++ b/membrane-esb/core/src/test/java/com/predic8/membrane/core/interceptor/rest/HTTP2XMLInterceptorTest.java
@@ -1,113 +1,114 @@
/* Copyright 2011, 2012 predic8 GmbH, www.predic8.com
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.predic8.membrane.core.interceptor.rest;
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import junit.framework.TestCase;
import org.junit.Test;
import org.xml.sax.InputSource;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.xml.Param;
import com.predic8.membrane.core.http.xml.Path;
import com.predic8.membrane.core.http.xml.Query;
import com.predic8.membrane.core.http.xml.Request;
import com.predic8.membrane.core.http.xml.URI;
import com.predic8.membrane.core.util.MessageUtil;
public class HTTP2XMLInterceptorTest extends TestCase {
private Exchange exc;
private HTTP2XMLInterceptor interceptor = new HTTP2XMLInterceptor();
XPath xpath = XPathFactory.newInstance().newXPath();
@Override
protected void setUp() throws Exception {
exc = new Exchange(null);
exc.setRequest(MessageUtil.getGetRequest("http://localhost/axis2/services/BLZService?wsdl"));
exc.getRequest().setUri("http://localhost:3011/manager/person?vorname=jim&nachname=panse");
exc.getRequest().setMethod("POST");
exc.getRequest().setVersion("1.1");
exc.getRequest().getHeader().add("Host", "localhost:3011");
}
@Test
public void testRequest() throws Exception {
interceptor.handleRequest(exc);
- assertXPath("/request/@method", "POST");
- assertXPath("/request/@http-version", "1.1");
- assertXPath("/request/uri/@value", "http://localhost:3011/manager/person?vorname=jim&nachname=panse");
- assertXPath("/request/uri/path/component[1]", "manager");
- assertXPath("/request/uri/path/component[2]", "person");
- assertXPath("/request/uri/query/param[@name='vorname']", "jim");
- assertXPath("/request/uri/query/param[@name='nachname']", "panse");
- assertXPath("/request/headers/header[@name='Host']", "localhost:3011");
+ assertXPath("local-name(/*)", "request");
+ assertXPath("/*/@method", "POST");
+ assertXPath("/*/@http-version", "1.1");
+ assertXPath("/*/uri/@value", "http://localhost:3011/manager/person?vorname=jim&nachname=panse");
+ assertXPath("/*/uri/path/component[1]", "manager");
+ assertXPath("/*/uri/path/component[2]", "person");
+ assertXPath("/*/uri/query/param[@name='vorname']", "jim");
+ assertXPath("/*/uri/query/param[@name='nachname']", "panse");
+ assertXPath("/*/headers/header[@name='Host']", "localhost:3011");
}
@Test
public void parseXML() throws Exception {
String xml = "<request method='POST' http-version='1.1'><uri value='http://localhost:3011/manager/person?vorname=jim&nachname=panse'><host>localhost</host><port>8080</port><path><component>manager</component><component>person</component></path><query><param name='vorname'>jim</param><param name='nachname'>panse</param></query></uri></request>";
XMLStreamReader r = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xml));
r.next(); //skip DocumentNode
Request req = new Request();
req.parse(r);
assertEquals("POST", req.getMethod());
assertEquals("1.1", req.getHttpVersion());
assertURI(req.getUri());
}
private void assertURI(URI uri) {
assertEquals("http://localhost:3011/manager/person?vorname=jim&nachname=panse", uri.getValue());
assertEquals("localhost", uri.getHost());
assertEquals(3011, uri.getPort());
assertPath(uri.getPath());
assertQuery(uri.getQuery());
}
private void assertQuery(Query query) {
assertParam("vorname", "jim", query.getParams().get(0));
assertParam("nachname", "panse", query.getParams().get(1));
}
private void assertParam(String name, String value, Param param) {
assertEquals(name, param.getName());
assertEquals(value, param.getValue());
}
private void assertPath(Path path) {
assertEquals("manager", path.getComponents().get(0).getValue());
assertEquals("person", path.getComponents().get(1).getValue());
}
private void assertXPath(String xpathExpr, String expected) throws XPathExpressionException {
assertEquals(expected, xpath.evaluate(xpathExpr, new InputSource(exc.getRequest().getBodyAsStream())));
}
}
| true | true | public void testRequest() throws Exception {
interceptor.handleRequest(exc);
assertXPath("/request/@method", "POST");
assertXPath("/request/@http-version", "1.1");
assertXPath("/request/uri/@value", "http://localhost:3011/manager/person?vorname=jim&nachname=panse");
assertXPath("/request/uri/path/component[1]", "manager");
assertXPath("/request/uri/path/component[2]", "person");
assertXPath("/request/uri/query/param[@name='vorname']", "jim");
assertXPath("/request/uri/query/param[@name='nachname']", "panse");
assertXPath("/request/headers/header[@name='Host']", "localhost:3011");
}
| public void testRequest() throws Exception {
interceptor.handleRequest(exc);
assertXPath("local-name(/*)", "request");
assertXPath("/*/@method", "POST");
assertXPath("/*/@http-version", "1.1");
assertXPath("/*/uri/@value", "http://localhost:3011/manager/person?vorname=jim&nachname=panse");
assertXPath("/*/uri/path/component[1]", "manager");
assertXPath("/*/uri/path/component[2]", "person");
assertXPath("/*/uri/query/param[@name='vorname']", "jim");
assertXPath("/*/uri/query/param[@name='nachname']", "panse");
assertXPath("/*/headers/header[@name='Host']", "localhost:3011");
}
|
diff --git a/galileo_openbook_cleaner/src/de/scrum_master/galileo/XOMClutterRemover.java b/galileo_openbook_cleaner/src/de/scrum_master/galileo/XOMClutterRemover.java
index 8acaf17..84eb32a 100644
--- a/galileo_openbook_cleaner/src/de/scrum_master/galileo/XOMClutterRemover.java
+++ b/galileo_openbook_cleaner/src/de/scrum_master/galileo/XOMClutterRemover.java
@@ -1,400 +1,400 @@
package de.scrum_master.galileo;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nu.xom.Attribute;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.Serializer;
import nu.xom.Text;
import nu.xom.XPathContext;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class XOMClutterRemover extends BasicConverter
{
private boolean isTOCFile; // TOC = table of contents = index.htm*
private XMLReader tagsoup; // plug-in XML reader for XOM
private Builder builder; // XOM document builder
private Document document; // XOM document (XML DOM structure)
private Element headTag; // XOM element pointing to HTML <head> tag
private Element bodyTag; // XOM element pointing to HTML <body> tag
private String pageTitle; // Content of HTML <title> tag
private boolean hasStandardLayout = true; // Known exception: "UNIX guru" book
private static final XPathContext context = // XOM XPath context for HTML
new XPathContext("html", "http://www.w3.org/1999/xhtml");
private static final Pattern REGEX_HREF = // Find subchapter no. in TOC link target
Pattern.compile("(.*_[0-9a-h]+_(?:[a-z0-9]+_)*)([0-9]+)(\\.htm.*)");
private static final Pattern REGEX_TEXT = // Find subchapter no. in TOC linkt title
Pattern.compile("^([0-9A-H]+\\.)([0-9]+)(.*)");
private static final String nonStandardCSS = // CSS style overrides for "UNIX guru" book
"body { font-size: 13px; }" +
"h1 a, h2 a, h3 a, h4 a { font-size: 16px; }" +
"pre { font-size: 12px; }";
private static enum XPath // XPath query strings mapped to symbolic names
{
HEAD ("//html:head"),
TITLE ("//html:head/html:title"),
SCRIPTS ("//html:script"),
BODY ("//html:body"),
BODY_NODES ("//html:body/node()"),
NON_STANDARD_MAIN_CONTENT ("//html:td[@class='buchtext']/node()"),
HEADING_1_TO_4 ("*[name()='h1' or name()='h2' or name()='h3' or name()='h4']"),
NON_STANDARD_TOP_NAVIGATION ("//html:body/" + HEADING_1_TO_4.query + "[1]/preceding-sibling::node()"),
NON_STANDARD_BOTTOM_NAVIGATION ("//html:div[@class='navigation']"),
GREY_TABLE ("//html:table[@bgcolor='#EEEEEE' or @bgcolor='#eeeeee']"),
MAIN_CONTENT_1 (GREY_TABLE.query + "/html:tr/html:td/html:div[@class='main']/node()|" +
GREY_TABLE.query + "/html:tbody/html:tr/html:td/html:div[@class='main']/node()"),
MAIN_CONTENT_2 (GREY_TABLE.query + "/html:tr/html:td/node()|" +
GREY_TABLE.query + "/html:tbody/html:tr/html:td/node()"),
JUMP_TO_TOP_LINK ("//html:div/html:a[@href='#top']/.."),
GRAPHICAL_PARAGRAPH_SEPARATOR ("//html:div/html:img[@src='common/jupiters.gif']/.."),
LAST_HR_TAG ("//html:hr[position()=last()]"),
AFTER_LAST_HR_TAG (LAST_HR_TAG.query + "/following-sibling::node()"),
FEEDBACK_FORM (LAST_HR_TAG.query + "|" + AFTER_LAST_HR_TAG.query),
FEEDBACK_FORM_URL_FIELD (AFTER_LAST_HR_TAG.query + "//html:input[@name='openbookurl']"),
IMAGE_SMALL ("//html:img[contains(@src,'klein/klein')]"),
IMAGE_1 ("//html:div[@class='bildbox']//html:img"),
IMAGE_2 ("//html:td[@class='tabellentext']//html:img"),
IMAGE_3 ("//html:a[@href='#bild']/html:img"),
IMAGE_4 ("//html:a[@rel='lightbox']/html:img"),
IMAGE_5 ("//html:a[contains(@onclick,'OpenWin')]/html:img"),
IMAGE_BOX_1 ("//html:div[@class='bildbox']"),
IMAGE_BOX_2 ("//html:td[@class='tabellentext']//html:img/../.."),
IMAGE_BOX_3 ("//html:a[@href='#bild']/html:img/../.."),
IMAGE_BOX_4 ("//html:a[@rel='lightbox']"),
IMAGE_BOX_5 ("//html:a[contains(@onclick,'OpenWin')]/html:img/.."),
TOC_HEADING_2 ("//html:h2/html:a/.."),
INDEX_LINK ("//html:a[contains(@href,'stichwort.htm')]"),
AFTER_INDEX_LINK (INDEX_LINK.query + "/following::node()"),
ALL_LINKS ("//html:a");
private final String query;
private XPath(String query)
{
this.query = query;
}
}
public XOMClutterRemover(InputStream in, OutputStream out, File origFile)
throws SAXException
{
super(in, out, origFile, "Removing clutter (header, footer, navigation, ads) and fixing structure");
isTOCFile = origFile.getName().startsWith("index.htm");
tagsoup = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");
builder = new Builder(tagsoup);
}
@Override
protected void convert() throws Exception
{
parseDocument();
removeClutter();
fixStructure();
writeDocument();
}
private void parseDocument() throws Exception
{
document = builder.build(in);
headTag = (Element) xPathQuery(XPath.HEAD.query).get(0);
bodyTag = (Element) xPathQuery(XPath.BODY.query).get(0);
pageTitle = xPathQuery(XPath.TITLE.query).get(0).getValue();
}
private void removeClutter()
{
fixNode429();
removeClutterAroundMainContent();
removeClutterWithinMainContent();
}
private void fixStructure()
{
if (!hasStandardLayout) {
fixFontSizesForNonStandardLayout();
return;
}
overrideBackgroundImage();
fixImages();
removeRedundantGreyTable();
if (isTOCFile) {
if (! hasIndexLink())
createIndexLink();
fixFaultyLinkTargets();
removeContentAfterIndexLink();
}
}
private void writeDocument() throws Exception
{
new Serializer(out, "ISO-8859-1").write(document);
}
/*
* Individual fix for a buggy heading in "Unix Guru" book's node429.html
* which would later make deletion of XPath.NON_STANDARD_TOP_NAVIGATION fail
* in method removeClutterWithinMainContent().
*/
private void fixNode429()
{
if (! (origFile.getName().equals("node429.html") && pageTitle.contains("UNIX-Guru")))
return;
SimpleLogger.verbose(" Fixing buggy heading...");
Element buggyParagraph = (Element) xPathQuery("//html:p[contains(text(),'gpGlossar18133')]").get(0);
Element heading = new Element("h1");
//heading.appendChild("unix");
bodyTag.appendChild(heading);
Element link = new Element("a");
link.appendChild("unix");
heading.appendChild(link);
replaceNodeBy(buggyParagraph, heading);
}
private void removeClutterAroundMainContent()
{
// Keep JavaScript for source code colouring ('prettyPrint' function) in some books
// deleteNodes(XPath.SCRIPTS.query);
Nodes mainContent = xPathQuery(XPath.NON_STANDARD_MAIN_CONTENT.query);
if (mainContent.size() > 0)
hasStandardLayout = false;
else {
mainContent = xPathQuery(XPath.MAIN_CONTENT_1.query);
if (mainContent.size() == 0)
mainContent = xPathQuery(XPath.MAIN_CONTENT_2.query);
}
deleteNodes(XPath.BODY_NODES.query);
moveNodesTo(mainContent, bodyTag);
}
private void removeClutterWithinMainContent()
{
if (hasStandardLayout) {
deleteNodes(XPath.JUMP_TO_TOP_LINK.query);
deleteNodes(XPath.GRAPHICAL_PARAGRAPH_SEPARATOR.query);
if (xPathQuery(XPath.FEEDBACK_FORM_URL_FIELD.query).size() > 0)
deleteNodes(XPath.FEEDBACK_FORM.query);
}
else {
deleteNodes(XPath.NON_STANDARD_TOP_NAVIGATION.query);
deleteNodes(XPath.NON_STANDARD_BOTTOM_NAVIGATION.query);
}
}
private void overrideBackgroundImage()
{
bodyTag.addAttribute(new Attribute("style", "background: none"));
}
private void fixImages()
{
replaceByBigImages(xPathQuery(XPath.IMAGE_SMALL.query));
replaceBoxesByImages(xPathQuery(XPath.IMAGE_BOX_1.query), xPathQuery(XPath.IMAGE_1.query));
replaceBoxesByImages(xPathQuery(XPath.IMAGE_BOX_2.query), xPathQuery(XPath.IMAGE_2.query));
replaceBoxesByImages(xPathQuery(XPath.IMAGE_BOX_3.query), xPathQuery(XPath.IMAGE_3.query));
replaceBoxesByImages(xPathQuery(XPath.IMAGE_BOX_4.query), xPathQuery(XPath.IMAGE_4.query));
replaceBoxesByImages(xPathQuery(XPath.IMAGE_BOX_5.query), xPathQuery(XPath.IMAGE_5.query));
}
/*
* There is one known occurrence (the "PHP PEAR" book) where there are two grey tables
* (background colour #eeeeee) within one document. It is actually a bug in the book's
* TOC (index.htm) because there are three lines of HTML code which are repeated erroneously.
* JTidy interprets them as two nested tables, handling them gracefully. But after
* removeClutterAroundMainContent() there still is a leftover grey table which needs
* to be removed. This is done here.
*/
private void removeRedundantGreyTable()
{
deleteNodes(XPath.GREY_TABLE.query);
}
/*
* Font sizes for non-standard layout book "UNIX guru" are too small in general and
* for page heading in particular. Fix it by adding a custom CSS style tag to each page.
*/
private void fixFontSizesForNonStandardLayout()
{
Element styleTag = new Element("style");
styleTag.addAttribute(new Attribute("type", "text/css"));
styleTag.appendChild(nonStandardCSS);
headTag.appendChild(styleTag);
}
/*
* Find out if this page contains a link to the index (stichwort.htm*).
*/
private boolean hasIndexLink()
{
return xPathQuery(XPath.INDEX_LINK.query).size() > 0;
}
/**
* Many Galileo Openbooks' tables of contents (TOC, index.htm*) are missing
* links to their respective indexes (stichwort.htm*).
*
* This is a problem because after clean-up there is no direct way to reach
* the index other than from the TOC. This also results in missing pages within
* EPUB books created by Calibre, for example. So we need to do something about it,
* i.e. insert missing links at the end of the respective TOC.
*/
private void createIndexLink()
{
if (pageTitle.contains("Ruby on Rails")) {
SimpleLogger.verbose(" TOC file: not creating index link (no stichwort.htm*");
return;
}
SimpleLogger.verbose(" TOC file: creating index link...");
Element indexLink = (Element) xPathQuery(XPath.TOC_HEADING_2.query).get(0).copy();
String fileExtension = ".htm";
if (((Element) indexLink.getChild(0)).getAttribute("href").getValue().contains(".html"))
fileExtension = ".html";
((Element) indexLink.getChild(0)).getAttribute("href").setValue("stichwort" + fileExtension);
((Text) indexLink.getChild(0).getChild(0)).setValue("Index");
bodyTag.appendChild(indexLink);
}
/**
* There is a strange quirk in the table of contents (TOC, index.htm*) of
* several (ca. 10) Galileo Openbooks:
*
* Some links for subchapters *.x point to the file for subchapter *.(x-1).
* The problem there is that after we have removed the surrounding clutter,
* there is no more redundant TOC column on the left, so there is no direct way
* to reach the missing chapters which have no reference in the TOC. This also
* results in missing pages within EPUB books created by Calibre, for example.
* So we need to do something about it, i.e. detect and fix the faulty links.
*
* Faulty example (abbreviated) from "Ubuntu 11.04" book:
* <pre>
* <a href="ubuntu_01_001.htm">1.2.* Blah</a>
* </pre>
* For chapter x.2.* the href must be corrected to ubuntu_0x_002.htm.
*
* It further complicates the fixing task that there are some (ca. 2) books
* which show a similar one-off behaviour for <i>all</i> subchapters by design,
* because they have a different numbering scheme. Those books are OK, though,
* thus we need to explicitly exclude them from "fixing". <tt>:-(</tt>
*/
private void fixFaultyLinkTargets()
{
SimpleLogger.verbose(" Checking for faulty TOC link targets...");
- SimpleLogger.verbose(" Book title = " + pageTitle);
+ SimpleLogger.verbose(" Page title = " + pageTitle);
// Exclude the 3 know exceptions and immediately return if one is found
if (pageTitle.matches(".*(ActionScript 1 und 2|Microsoft-Netzwerk|Shell-Programmierung).*")) {
SimpleLogger.verbose(" Book title is an exception - no link fixing done");
return;
}
int fixedLinksCount = 0;
Nodes links = xPathQuery(XPath.ALL_LINKS.query);
for (int i = 0; i < links.size(); i++) {
Element link = (Element) links.get(i);
String href = link.getAttributeValue("href");
String text = link.getValue();
Matcher hrefMatcher = REGEX_HREF.matcher(href);
Matcher textMatcher = REGEX_TEXT.matcher(text);
if (hrefMatcher.matches() && textMatcher.matches()) {
int hrefNumber = Integer.parseInt(hrefMatcher.group(2));
int textNumber = Integer.parseInt(textMatcher.group(2));
if (hrefNumber != textNumber) {
SimpleLogger.debug(" Chapter " + text);
SimpleLogger.debug(" Faulty: " + href);
String numberFormat = "%0" + hrefMatcher.group(2).length() + "d";
href=hrefMatcher.group(1) + String.format(numberFormat, textNumber) + hrefMatcher.group(3);
SimpleLogger.debug(" Fixed: " + href);
link.getAttribute("href").setValue(href);
fixedLinksCount++;
}
}
}
SimpleLogger.verbose(" Number of fixed links = " + fixedLinksCount);
}
/*
* There is one known occurrence (the "JavaScript and AJAX" book) where there is
* erroneous trailing text after the last TOC entry (the index link pointing to
* stichwort.htm*). Because it looks ugly, we remove everything after the index link.
*/
private void removeContentAfterIndexLink()
{
deleteNodes(XPath.AFTER_INDEX_LINK.query);
}
private static void replaceByBigImages(Nodes smallImages)
{
for (int i = 0; i < smallImages.size(); i++) {
Attribute imageSrc = ((Element) smallImages.get(i)).getAttribute("src");
imageSrc.setValue(imageSrc.getValue().replaceFirst("klein/klein", "/"));
}
}
private static void replaceBoxesByImages(Nodes smallImageBoxes, Nodes smallImages)
{
for (int i = 0; i < smallImageBoxes.size(); i++)
replaceNodeBy(smallImageBoxes.get(i), smallImages.get(i));
}
/*
* ============================================================================================
* GENERAL PURPOSE HELPER METHODS
* ============================================================================================
*/
private Nodes xPathQuery(String query)
{
return document.query(query, context);
}
private static void deleteNodes(Nodes nodes)
{
for (int i = 0; i < nodes.size(); i++)
nodes.get(i).detach();
}
private void deleteNodes(String xPathQuery)
{
deleteNodes(xPathQuery(xPathQuery));
}
private static void moveNodesTo(Nodes sourceNodes, Element targetElement)
{
for (int i = 0; i < sourceNodes.size(); i++) {
sourceNodes.get(i).detach();
targetElement.appendChild(sourceNodes.get(i));
}
}
private static void replaceNodeBy(Node original, Node replacement)
{
replacement.detach();
original.getParent().replaceChild(original, replacement);
}
}
| true | true | private void fixFaultyLinkTargets()
{
SimpleLogger.verbose(" Checking for faulty TOC link targets...");
SimpleLogger.verbose(" Book title = " + pageTitle);
// Exclude the 3 know exceptions and immediately return if one is found
if (pageTitle.matches(".*(ActionScript 1 und 2|Microsoft-Netzwerk|Shell-Programmierung).*")) {
SimpleLogger.verbose(" Book title is an exception - no link fixing done");
return;
}
int fixedLinksCount = 0;
Nodes links = xPathQuery(XPath.ALL_LINKS.query);
for (int i = 0; i < links.size(); i++) {
Element link = (Element) links.get(i);
String href = link.getAttributeValue("href");
String text = link.getValue();
Matcher hrefMatcher = REGEX_HREF.matcher(href);
Matcher textMatcher = REGEX_TEXT.matcher(text);
if (hrefMatcher.matches() && textMatcher.matches()) {
int hrefNumber = Integer.parseInt(hrefMatcher.group(2));
int textNumber = Integer.parseInt(textMatcher.group(2));
if (hrefNumber != textNumber) {
SimpleLogger.debug(" Chapter " + text);
SimpleLogger.debug(" Faulty: " + href);
String numberFormat = "%0" + hrefMatcher.group(2).length() + "d";
href=hrefMatcher.group(1) + String.format(numberFormat, textNumber) + hrefMatcher.group(3);
SimpleLogger.debug(" Fixed: " + href);
link.getAttribute("href").setValue(href);
fixedLinksCount++;
}
}
}
SimpleLogger.verbose(" Number of fixed links = " + fixedLinksCount);
}
| private void fixFaultyLinkTargets()
{
SimpleLogger.verbose(" Checking for faulty TOC link targets...");
SimpleLogger.verbose(" Page title = " + pageTitle);
// Exclude the 3 know exceptions and immediately return if one is found
if (pageTitle.matches(".*(ActionScript 1 und 2|Microsoft-Netzwerk|Shell-Programmierung).*")) {
SimpleLogger.verbose(" Book title is an exception - no link fixing done");
return;
}
int fixedLinksCount = 0;
Nodes links = xPathQuery(XPath.ALL_LINKS.query);
for (int i = 0; i < links.size(); i++) {
Element link = (Element) links.get(i);
String href = link.getAttributeValue("href");
String text = link.getValue();
Matcher hrefMatcher = REGEX_HREF.matcher(href);
Matcher textMatcher = REGEX_TEXT.matcher(text);
if (hrefMatcher.matches() && textMatcher.matches()) {
int hrefNumber = Integer.parseInt(hrefMatcher.group(2));
int textNumber = Integer.parseInt(textMatcher.group(2));
if (hrefNumber != textNumber) {
SimpleLogger.debug(" Chapter " + text);
SimpleLogger.debug(" Faulty: " + href);
String numberFormat = "%0" + hrefMatcher.group(2).length() + "d";
href=hrefMatcher.group(1) + String.format(numberFormat, textNumber) + hrefMatcher.group(3);
SimpleLogger.debug(" Fixed: " + href);
link.getAttribute("href").setValue(href);
fixedLinksCount++;
}
}
}
SimpleLogger.verbose(" Number of fixed links = " + fixedLinksCount);
}
|
diff --git a/src/net/aufdemrand/denizen/utilities/GetRequirements.java b/src/net/aufdemrand/denizen/utilities/GetRequirements.java
index df04a982a..41019ec97 100644
--- a/src/net/aufdemrand/denizen/utilities/GetRequirements.java
+++ b/src/net/aufdemrand/denizen/utilities/GetRequirements.java
@@ -1,163 +1,175 @@
package net.aufdemrand.denizen.utilities;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import net.aufdemrand.denizen.Denizen;
import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
public class GetRequirements {
public enum RequirementMode {
NONE, ALL, ANY
}
public enum Requirement {
NONE, NAME, WEARING, ITEM, HOLDING, TIME, PRECIPITATION, ACTIVITY, FINISHED, SCRIPT, FAILED,
STORMY, SUNNY, HUNGER, WORLD, PERMISSION, LEVEL, GROUP, MONEY, POTIONEFFECT, PRECIPITATING,
STORMING
}
@SuppressWarnings("null")
public boolean check(String theScript, LivingEntity theEntity, boolean isPlayer) {
Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
String requirementMode = plugin.getScripts().getString(theScript + ".Requirements.Mode");
List<String> requirementList = plugin.getScripts().getStringList(theScript + ".Requirements.List");
/* No requirements met yet, we just started! */
int numberMet = 0;
boolean negativeRequirement;
/* Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE */
if (requirementMode.equalsIgnoreCase("NONE") || requirementList.isEmpty()) return true;
for (String requirementEntry : requirementList) {
/* Check if this is a Negative Requirement */
if (requirementEntry.startsWith("-")) {
negativeRequirement = true;
requirementEntry = requirementEntry.substring(1);
}
else negativeRequirement = false;
String[] arguments = new String[25];
arguments = requirementEntry.split(" ");
switch (Requirement.valueOf(arguments[0].toUpperCase())) {
case NONE:
return true;
case TIME: // (-)TIME [DAWN|DAY|DUSK|NIGHT] or (-)TIME [#] [#]
if (Denizen.getWorld.checkTime(theEntity.getWorld(), arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case STORMING: case STORMY: case PRECIPITATING: case PRECIPITATION: // (-)PRECIPITATION
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "PRECIPITATION", negativeRequirement)) numberMet++;
break;
case SUNNY: // (-)SUNNY
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "SUNNY", negativeRequirement)) numberMet++;
break;
case HUNGER: // (-)HUNGER [FULL|HUNGRY|STARVING]
if (Denizen.getPlayer.checkSaturation((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case LEVEL: // (-)LEVEL [#] (#)
if (Denizen.getPlayer.checkLevel((Player) theEntity, arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WORLD: // (-)WORLD [List of Worlds]
- List<String> theWorlds = Arrays.asList(arguments);
+ List<String> theWorlds = new LinkedList<String>(); // = Arrays.asList(arguments);
+ for(String arg : arguments) {
+ theWorlds.add(arg);
+ }
theWorlds.remove(0); /* Remove the command from the list */
if (Denizen.getWorld.checkWorld(theEntity, theWorlds, negativeRequirement)) numberMet++;
break;
case NAME: // (-)Name [List of Names]
- List<String> theNames = Arrays.asList(arguments);
+ List<String> theNames = new LinkedList<String>(); // = Arrays.asList(arguments);
+ for(String arg : arguments) {
+ theNames.add(arg);
+ }
theNames.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkName((Player) theEntity, theNames, negativeRequirement)) numberMet++;
break;
case MONEY: // (-)MONEY [# or more]
if (Denizen.getPlayer.checkFunds((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case ITEM: // (-)ITEM [ITEM_NAME|#:#] (# or more)
String[] itemArgs = new String[1];
itemArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkInventory((Player) theEntity, itemArgs[0], itemArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case HOLDING: // (-)HOLDING [ITEM_NAME|#:#] (# or more)
String[] holdingArgs = new String[1];
holdingArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkHand((Player) theEntity, holdingArgs[0], holdingArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WEARING: // (-) WEARING [ITEM_NAME|#]
if (Denizen.getPlayer.checkArmor((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case POTIONEFFECT: // (-)POTIONEFFECT [List of POITION_TYPESs]
- List<String> thePotions = Arrays.asList(arguments);
+ List<String> thePotions = new LinkedList<String>(); // = Arrays.asList(arguments);
+ for(String arg : arguments) {
+ thePotions.add(arg);
+ }
thePotions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkEffects((Player) theEntity, thePotions, negativeRequirement)) numberMet++;
break;
case FINISHED:
case SCRIPT: // (-)FINISHED (#) [Script Name]
if (Denizen.getScript.getScriptCompletes((Player) theEntity, requirementEntry.split(" ", 2)[1], requirementEntry.split(" ", 3)[1], negativeRequirement)) numberMet++;
break;
case FAILED: // (-)SCRIPT [Script Name]
if (Denizen.getScript.getScriptFail((Player) theEntity, requirementEntry.split(" ", 2)[1], negativeRequirement))
break;
case GROUP:
List<String> theGroups = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
theGroups.add(arg);
}
theGroups.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkGroups((Player) theEntity, theGroups, negativeRequirement)) numberMet++;
break;
case PERMISSION: // (-)PERMISSION [this.permission.node]
- List<String> thePermissions = Arrays.asList(arguments);
+ List<String> thePermissions = new LinkedList<String>(); // = Arrays.asList(arguments);
+ for(String arg : arguments) {
+ thePermissions.add(arg);
+ }
thePermissions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkPermissions((Player) theEntity, thePermissions, negativeRequirement)) numberMet++;
break;
}
}
/* Check numberMet */
if (requirementMode.equalsIgnoreCase("ALL")
&& numberMet == requirementList.size()) return true;
String[] ModeArgs = requirementMode.split(" ");
if (ModeArgs[0].equalsIgnoreCase("ANY")
&& numberMet >= Integer.parseInt(ModeArgs[1])) return true;
/* Nothing met, return FALSE */
return false;
}
}
| false | true | public boolean check(String theScript, LivingEntity theEntity, boolean isPlayer) {
Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
String requirementMode = plugin.getScripts().getString(theScript + ".Requirements.Mode");
List<String> requirementList = plugin.getScripts().getStringList(theScript + ".Requirements.List");
/* No requirements met yet, we just started! */
int numberMet = 0;
boolean negativeRequirement;
/* Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE */
if (requirementMode.equalsIgnoreCase("NONE") || requirementList.isEmpty()) return true;
for (String requirementEntry : requirementList) {
/* Check if this is a Negative Requirement */
if (requirementEntry.startsWith("-")) {
negativeRequirement = true;
requirementEntry = requirementEntry.substring(1);
}
else negativeRequirement = false;
String[] arguments = new String[25];
arguments = requirementEntry.split(" ");
switch (Requirement.valueOf(arguments[0].toUpperCase())) {
case NONE:
return true;
case TIME: // (-)TIME [DAWN|DAY|DUSK|NIGHT] or (-)TIME [#] [#]
if (Denizen.getWorld.checkTime(theEntity.getWorld(), arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case STORMING: case STORMY: case PRECIPITATING: case PRECIPITATION: // (-)PRECIPITATION
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "PRECIPITATION", negativeRequirement)) numberMet++;
break;
case SUNNY: // (-)SUNNY
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "SUNNY", negativeRequirement)) numberMet++;
break;
case HUNGER: // (-)HUNGER [FULL|HUNGRY|STARVING]
if (Denizen.getPlayer.checkSaturation((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case LEVEL: // (-)LEVEL [#] (#)
if (Denizen.getPlayer.checkLevel((Player) theEntity, arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WORLD: // (-)WORLD [List of Worlds]
List<String> theWorlds = Arrays.asList(arguments);
theWorlds.remove(0); /* Remove the command from the list */
if (Denizen.getWorld.checkWorld(theEntity, theWorlds, negativeRequirement)) numberMet++;
break;
case NAME: // (-)Name [List of Names]
List<String> theNames = Arrays.asList(arguments);
theNames.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkName((Player) theEntity, theNames, negativeRequirement)) numberMet++;
break;
case MONEY: // (-)MONEY [# or more]
if (Denizen.getPlayer.checkFunds((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case ITEM: // (-)ITEM [ITEM_NAME|#:#] (# or more)
String[] itemArgs = new String[1];
itemArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkInventory((Player) theEntity, itemArgs[0], itemArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case HOLDING: // (-)HOLDING [ITEM_NAME|#:#] (# or more)
String[] holdingArgs = new String[1];
holdingArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkHand((Player) theEntity, holdingArgs[0], holdingArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WEARING: // (-) WEARING [ITEM_NAME|#]
if (Denizen.getPlayer.checkArmor((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case POTIONEFFECT: // (-)POTIONEFFECT [List of POITION_TYPESs]
List<String> thePotions = Arrays.asList(arguments);
thePotions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkEffects((Player) theEntity, thePotions, negativeRequirement)) numberMet++;
break;
case FINISHED:
case SCRIPT: // (-)FINISHED (#) [Script Name]
if (Denizen.getScript.getScriptCompletes((Player) theEntity, requirementEntry.split(" ", 2)[1], requirementEntry.split(" ", 3)[1], negativeRequirement)) numberMet++;
break;
case FAILED: // (-)SCRIPT [Script Name]
if (Denizen.getScript.getScriptFail((Player) theEntity, requirementEntry.split(" ", 2)[1], negativeRequirement))
break;
case GROUP:
List<String> theGroups = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
theGroups.add(arg);
}
theGroups.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkGroups((Player) theEntity, theGroups, negativeRequirement)) numberMet++;
break;
case PERMISSION: // (-)PERMISSION [this.permission.node]
List<String> thePermissions = Arrays.asList(arguments);
thePermissions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkPermissions((Player) theEntity, thePermissions, negativeRequirement)) numberMet++;
break;
}
}
/* Check numberMet */
if (requirementMode.equalsIgnoreCase("ALL")
&& numberMet == requirementList.size()) return true;
String[] ModeArgs = requirementMode.split(" ");
if (ModeArgs[0].equalsIgnoreCase("ANY")
&& numberMet >= Integer.parseInt(ModeArgs[1])) return true;
/* Nothing met, return FALSE */
return false;
}
| public boolean check(String theScript, LivingEntity theEntity, boolean isPlayer) {
Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
String requirementMode = plugin.getScripts().getString(theScript + ".Requirements.Mode");
List<String> requirementList = plugin.getScripts().getStringList(theScript + ".Requirements.List");
/* No requirements met yet, we just started! */
int numberMet = 0;
boolean negativeRequirement;
/* Requirement node "NONE"? No requirements in the LIST? No need to continue, return TRUE */
if (requirementMode.equalsIgnoreCase("NONE") || requirementList.isEmpty()) return true;
for (String requirementEntry : requirementList) {
/* Check if this is a Negative Requirement */
if (requirementEntry.startsWith("-")) {
negativeRequirement = true;
requirementEntry = requirementEntry.substring(1);
}
else negativeRequirement = false;
String[] arguments = new String[25];
arguments = requirementEntry.split(" ");
switch (Requirement.valueOf(arguments[0].toUpperCase())) {
case NONE:
return true;
case TIME: // (-)TIME [DAWN|DAY|DUSK|NIGHT] or (-)TIME [#] [#]
if (Denizen.getWorld.checkTime(theEntity.getWorld(), arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case STORMING: case STORMY: case PRECIPITATING: case PRECIPITATION: // (-)PRECIPITATION
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "PRECIPITATION", negativeRequirement)) numberMet++;
break;
case SUNNY: // (-)SUNNY
if (Denizen.getWorld.checkWeather(theEntity.getWorld(), "SUNNY", negativeRequirement)) numberMet++;
break;
case HUNGER: // (-)HUNGER [FULL|HUNGRY|STARVING]
if (Denizen.getPlayer.checkSaturation((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case LEVEL: // (-)LEVEL [#] (#)
if (Denizen.getPlayer.checkLevel((Player) theEntity, arguments[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WORLD: // (-)WORLD [List of Worlds]
List<String> theWorlds = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
theWorlds.add(arg);
}
theWorlds.remove(0); /* Remove the command from the list */
if (Denizen.getWorld.checkWorld(theEntity, theWorlds, negativeRequirement)) numberMet++;
break;
case NAME: // (-)Name [List of Names]
List<String> theNames = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
theNames.add(arg);
}
theNames.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkName((Player) theEntity, theNames, negativeRequirement)) numberMet++;
break;
case MONEY: // (-)MONEY [# or more]
if (Denizen.getPlayer.checkFunds((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case ITEM: // (-)ITEM [ITEM_NAME|#:#] (# or more)
String[] itemArgs = new String[1];
itemArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkInventory((Player) theEntity, itemArgs[0], itemArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case HOLDING: // (-)HOLDING [ITEM_NAME|#:#] (# or more)
String[] holdingArgs = new String[1];
holdingArgs = arguments[1].split(":", 2);
if (Denizen.getPlayer.checkHand((Player) theEntity, holdingArgs[0], holdingArgs[1], arguments[2], negativeRequirement)) numberMet++;
break;
case WEARING: // (-) WEARING [ITEM_NAME|#]
if (Denizen.getPlayer.checkArmor((Player) theEntity, arguments[1], negativeRequirement)) numberMet++;
break;
case POTIONEFFECT: // (-)POTIONEFFECT [List of POITION_TYPESs]
List<String> thePotions = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
thePotions.add(arg);
}
thePotions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkEffects((Player) theEntity, thePotions, negativeRequirement)) numberMet++;
break;
case FINISHED:
case SCRIPT: // (-)FINISHED (#) [Script Name]
if (Denizen.getScript.getScriptCompletes((Player) theEntity, requirementEntry.split(" ", 2)[1], requirementEntry.split(" ", 3)[1], negativeRequirement)) numberMet++;
break;
case FAILED: // (-)SCRIPT [Script Name]
if (Denizen.getScript.getScriptFail((Player) theEntity, requirementEntry.split(" ", 2)[1], negativeRequirement))
break;
case GROUP:
List<String> theGroups = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
theGroups.add(arg);
}
theGroups.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkGroups((Player) theEntity, theGroups, negativeRequirement)) numberMet++;
break;
case PERMISSION: // (-)PERMISSION [this.permission.node]
List<String> thePermissions = new LinkedList<String>(); // = Arrays.asList(arguments);
for(String arg : arguments) {
thePermissions.add(arg);
}
thePermissions.remove(0); /* Remove the command from the list */
if (Denizen.getPlayer.checkPermissions((Player) theEntity, thePermissions, negativeRequirement)) numberMet++;
break;
}
}
/* Check numberMet */
if (requirementMode.equalsIgnoreCase("ALL")
&& numberMet == requirementList.size()) return true;
String[] ModeArgs = requirementMode.split(" ");
if (ModeArgs[0].equalsIgnoreCase("ANY")
&& numberMet >= Integer.parseInt(ModeArgs[1])) return true;
/* Nothing met, return FALSE */
return false;
}
|
diff --git a/tools/KeggConverter/src/org/pathvisio/kegg/Util.java b/tools/KeggConverter/src/org/pathvisio/kegg/Util.java
index 08393a1a..1ebfd81f 100644
--- a/tools/KeggConverter/src/org/pathvisio/kegg/Util.java
+++ b/tools/KeggConverter/src/org/pathvisio/kegg/Util.java
@@ -1,221 +1,221 @@
//PathVisio,
//a tool for data visualization and analysis using Biological Pathways
//Copyright 2006-2007 BiGCaT Bioinformatics
//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.pathvisio.kegg;
import java.awt.geom.Point2D;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.bridgedb.Organism;
import org.pathvisio.debug.Logger;
import org.pathvisio.model.ConverterException;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.GraphLink.GraphIdContainer;
import org.pathvisio.view.LinAlg;
import org.pathvisio.view.LinAlg.Point;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
public class Util {
static String getKeggOrganism(Organism organism) throws ConverterException {
switch(organism) {
case HomoSapiens:
return "hsa";
case RattusNorvegicus:
return "rno";
case MusMusculus:
return "mmu";
case SaccharomycesCerevisiae:
return "sce";
case ArabidopsisThaliana:
return "ath";
case BosTaurus:
return "bta";
case CaenorhabditisElegans:
return "cel";
case CanisFamiliaris:
return "cfa";
- case DanioRero:
+ case DanioRerio:
return "dre";
case DrosophilaMelanogaster:
return "dme";
case EscherichiaColi:
return "eco";
case GallusGallus:
return "gga";
case OryzaSativa:
return "osa";
case TriticumAestivum:
return "etae";
case XenopusTropicalis:
return "xtr";
case ZeaMays:
return "ezma";
default:
throw new ConverterException("No KEGG code for organism " + organism);
}
}
static String getGraphId(GraphIdContainer gc) {
//TK: Quick hack, GraphId is not automatically generated,
//so set one explicitly...
String id = gc.getGraphId();
if(id == null) {
gc.setGraphId(id = gc.getGmmlData().getUniqueGraphId());
}
return id;
}
static void stackElements(Collection<PathwayElement> pwElms) {
PathwayElement[] elements = pwElms.toArray(new PathwayElement[pwElms.size()]);
PathwayElement center = elements[0];
double currAbove = center.getMTop();
double currBelow = center.getMTop() + center.getMHeight();
for(int i = 1; i < pwElms.size(); i++) {
PathwayElement e = elements[i];
if(i % 2 == 0) { //Place below
e.setMTop(currBelow);
currBelow += e.getMHeight();
} else { //Place above
currAbove -= e.getMHeight();
e.setMTop(currAbove);
}
}
}
static Point[] findBorders(GraphIdContainer start, GraphIdContainer end) {
Point2D csource = start.toAbsoluteCoordinate(new Point2D.Double(0, 0));
Point2D ctarget = end.toAbsoluteCoordinate(new Point2D.Double(0, 0));
Point psource = new Point(csource.getX(), csource.getY());
Point ptarget = new Point(ctarget.getX(), ctarget.getY());
double angle = LinAlg.angle(ptarget.subtract(psource), new Point(1, 0));
double astart = angle;
double aend = angle;
if(angle < 0) aend += Math.PI;
else aend -= Math.PI;
if(angle == 0) {
if(psource.x > ptarget.x) {
aend += Math.PI;
astart += Math.PI;
}
}
Point pstart = findBorder(start, astart);
Point pend = findBorder(end, aend);
return new Point[] { pstart, pend };
}
/**
* Find the border to connect to. Returns a point containing
* the relative coordinates.
*/
static Point findBorder(GraphIdContainer gc, double angle) {
Point bp = new Point(-1, -1);
Point2D topleft = gc.toAbsoluteCoordinate(new Point2D.Double(-1, -1));
Point2D btmright = gc.toAbsoluteCoordinate(new Point2D.Double(1, 1));
double h = btmright.getY() - topleft.getY();
double w = btmright.getX() - topleft.getX();
double diagAngle = Math.atan(h / w);
double angleA = Math.abs(angle);
/* da < |a| < da + pi/2
\ /
\ /
|a| > da + pi/2 \ |a| < da
/ \
/ \
da < |a| < da + pi/2
*/
if(angleA >= diagAngle && angleA <= diagAngle + Math.PI/2) {
bp.x = 0; //center
if(angle < 0) {
bp.y += 2;
}
}
if(angleA < diagAngle || angleA > diagAngle + Math.PI/2) {
bp.y = 0;
if(angle < Math.PI / 2 && angle > -Math.PI / 2) {
bp.x += 2;
}
}
return bp;
}
//From http://iq80.com/2007/10/disable-dtd-and-xsd-downloading.html
public static Object unmarshal(Class type, InputStream in) throws ParserConfigurationException, SAXException, JAXBException {
// create a parser with validation disabled
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
// Get the JAXB context -- this should be cached
JAXBContext ctx = JAXBContext.newInstance(type);
// get the unmarshaller
Unmarshaller unmarshaller = ctx.createUnmarshaller();
// log errors?
unmarshaller.setEventHandler(new ValidationEventHandler(){
public boolean handleEvent(ValidationEvent validationEvent) {
Logger.log.warn(validationEvent.getMessage());
return false;
}
});
// add our XMLFilter which disables dtd downloading
NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
// Wrap the input stream with our filter
SAXSource source = new SAXSource(xmlFilter, new InputSource(in));
// unmarshal the document
return unmarshaller.unmarshal(source);
}
private static class NamespaceFilter extends XMLFilterImpl {
private static final InputSource EMPTY_INPUT_SOURCE =
new InputSource(new ByteArrayInputStream(new byte[0]));
public NamespaceFilter(XMLReader xmlReader) {
super(xmlReader);
}
public InputSource resolveEntity(String publicId, String systemId) {
return EMPTY_INPUT_SOURCE;
}
}
}
| true | true | static String getKeggOrganism(Organism organism) throws ConverterException {
switch(organism) {
case HomoSapiens:
return "hsa";
case RattusNorvegicus:
return "rno";
case MusMusculus:
return "mmu";
case SaccharomycesCerevisiae:
return "sce";
case ArabidopsisThaliana:
return "ath";
case BosTaurus:
return "bta";
case CaenorhabditisElegans:
return "cel";
case CanisFamiliaris:
return "cfa";
case DanioRero:
return "dre";
case DrosophilaMelanogaster:
return "dme";
case EscherichiaColi:
return "eco";
case GallusGallus:
return "gga";
case OryzaSativa:
return "osa";
case TriticumAestivum:
return "etae";
case XenopusTropicalis:
return "xtr";
case ZeaMays:
return "ezma";
default:
throw new ConverterException("No KEGG code for organism " + organism);
}
}
| static String getKeggOrganism(Organism organism) throws ConverterException {
switch(organism) {
case HomoSapiens:
return "hsa";
case RattusNorvegicus:
return "rno";
case MusMusculus:
return "mmu";
case SaccharomycesCerevisiae:
return "sce";
case ArabidopsisThaliana:
return "ath";
case BosTaurus:
return "bta";
case CaenorhabditisElegans:
return "cel";
case CanisFamiliaris:
return "cfa";
case DanioRerio:
return "dre";
case DrosophilaMelanogaster:
return "dme";
case EscherichiaColi:
return "eco";
case GallusGallus:
return "gga";
case OryzaSativa:
return "osa";
case TriticumAestivum:
return "etae";
case XenopusTropicalis:
return "xtr";
case ZeaMays:
return "ezma";
default:
throw new ConverterException("No KEGG code for organism " + organism);
}
}
|
diff --git a/edu/mit/wi/haploview/HaploData.java b/edu/mit/wi/haploview/HaploData.java
index 96e939f..89f7fba 100644
--- a/edu/mit/wi/haploview/HaploData.java
+++ b/edu/mit/wi/haploview/HaploData.java
@@ -1,2271 +1,2271 @@
package edu.mit.wi.haploview;
import edu.mit.wi.pedfile.*;
import java.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;
import java.text.NumberFormat;
import java.net.URL;
import java.net.MalformedURLException;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class HaploData implements Constants{
private Vector chromosomes;
private Vector extraTrioChromosomes;
private Haplotype[][] haplotypes;
private Haplotype[][] rawHaplotypes;
Vector blocks;
boolean[] isInBlock;
boolean infoKnown = false;
boolean blocksChanged = false;
public DPrimeTable dpTable;
private PedFile pedFile;
public boolean finished = false;
private double[] percentBadGenotypes;
XYSeriesCollection analysisTracks = new XYSeriesCollection();
boolean trackExists = false;
boolean dupsToBeFlagged = false, dupNames = false;
//stuff for computing d prime
private int AA = 0;
private int AB = 1;
private int BA = 2;
private int BB = 3;
private double TOLERANCE = 0.00000001;
private double LN10 = Math.log(10.0);
int unknownDH=-1;
int total_chroms=-1;
double const_prob=-1.0;
double[] known = new double[5];
double[] numHaps = new double[4];
double[] probHaps = new double[4];
//These are iterators for the progress bar.
int dPrimeTotalCount = -1;
int dPrimeCount;
private static boolean phasedData = false;
public int numTrios, numSingletons,numPeds;
public PedFile getPedFile(){
return this.pedFile;
}
void prepareMarkerInput(InputStream inStream, String[][] hapmapGoodies) throws IOException, HaploViewException{
//this method is called to gather data about the markers used.
//It is assumed that the input file is two columns, the first being
//the name and the second the absolute position. the maxdist is
//used to determine beyond what distance comparisons will not be
//made. if the infile param is null, loads up "dummy info" for
//situation where no info file exists
//An optional third column is supported which is designed to hold
//association study data. If there is a third column there will be
//a visual indicator in the D' display that there is additional data
//and the detailed data can be viewed with a mouse press.
Vector names = new Vector();
HashSet nameSearch = new HashSet();
HashSet dupCheck = new HashSet();
Vector positions = new Vector();
Vector extras = new Vector();
boolean infoProblem = false;
dupsToBeFlagged = false;
dupNames = false;
try{
if (inStream != null){
//read the input file:
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String currentLine;
long prevloc = -1000000000;
int lineCount = 0;
while ((currentLine = in.readLine()) != null){
StringTokenizer st = new StringTokenizer(currentLine);
if (st.countTokens() > 1){
lineCount++;
}else if (st.countTokens() == 1){
//complain if only one field found
throw new HaploViewException("Info file format error on line "+lineCount+
":\n Info file must be of format: <markername> <markerposition>");
}else{
//skip blank lines
continue;
}
String name = st.nextToken();
String l = st.nextToken();
String extra = null;
if (st.hasMoreTokens()) extra = st.nextToken();
long loc;
try{
loc = Long.parseLong(l);
}catch (NumberFormatException nfe){
infoProblem = true;
throw new HaploViewException("Info file format error on line "+lineCount+
":\n\"" + l + "\" should be of type long." +
"\n Info file must be of format: <markername> <markerposition>");
}
//basically if anyone is crazy enough to load a dataset, then go back and load
//an out-of-order info file we tell them to bugger off and start over.
if (loc < prevloc && Chromosome.markers != null){
infoProblem = true;
throw new HaploViewException("Info file out of order with preloaded dataset:\n"+
name + "\nPlease reload data file and info file together.");
}
prevloc = loc;
if (nameSearch.contains(name)){
dupCheck.add(name);
}
names.add(name);
nameSearch.add(name);
positions.add(l);
extras.add(extra);
}
if (lineCount > Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file compared to data file."));
}
if (lineCount < Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file compared to data file."));
}
infoKnown=true;
}
if (hapmapGoodies != null){
//we know some stuff from the hapmap so we'll add it here
for (int x=0; x < hapmapGoodies.length; x++){
if (nameSearch.contains(hapmapGoodies[x][0])){
dupCheck.add(hapmapGoodies[x][0]);
}
names.add(hapmapGoodies[x][0]);
nameSearch.add(hapmapGoodies[x][0]);
positions.add(hapmapGoodies[x][1]);
extras.add(null);
}
infoKnown = true;
}
if(dupCheck.size() > 0) {
int nameCount = names.size();
Hashtable dupCounts = new Hashtable();
for(int i=0;i<nameCount;i++) {
if(dupCheck.contains(names.get(i))){
String n = (String) names.get(i);
if(dupCounts.containsKey(n)){
int numDups = ((Integer) dupCounts.get(n)).intValue();
String newName = n + "." + numDups;
while (nameSearch.contains(newName)){
numDups++;
newName = n + "." + numDups;
}
names.setElementAt(newName,i);
nameSearch.add(newName);
dupCounts.put(n,new Integer(numDups)) ;
}else {
//we leave the first instance with its original name
dupCounts.put(n,new Integer(1));
}
dupNames = true;
}
}
}
//sort the markers
int numLines = names.size();
class SortingHelper implements Comparable{
long pos;
int orderInFile;
public SortingHelper(long pos, int order){
this.pos = pos;
this.orderInFile = order;
}
public int compareTo(Object o) {
SortingHelper sh = (SortingHelper)o;
if (sh.pos > pos){
return -1;
}else if (sh.pos < pos){
return 1;
}else{
return 0;
}
}
}
boolean needSort = false;
Vector sortHelpers = new Vector();
for (int k = 0; k < (numLines); k++){
sortHelpers.add(new SortingHelper(Long.parseLong((String)positions.get(k)),k));
}
//loop through and check if any markers are out of order
for (int k = 1; k < (numLines); k++){
if(((SortingHelper)sortHelpers.get(k)).compareTo(sortHelpers.get(k-1)) < 0) {
needSort = true;
break;
}
}
//if any were out of order, then we need to put them in order
if(needSort){
//throw new HaploViewException("unsorted files not supported at present");
//sort the positions
Collections.sort(sortHelpers);
Vector newNames = new Vector();
Vector newExtras = new Vector();
Vector newPositions = new Vector();
int[] realPos = new int[numLines];
//reorder the vectors names and extras so that they have the same order as the sorted markers
for (int i = 0; i < sortHelpers.size(); i++){
realPos[i] = ((SortingHelper)sortHelpers.get(i)).orderInFile;
newNames.add(names.get(realPos[i]));
newPositions.add(positions.get(realPos[i]));
newExtras.add(extras.get(realPos[i]));
}
names = newNames;
extras = newExtras;
positions = newPositions;
byte[] tempGenotype = new byte[sortHelpers.size()];
//now we reorder all the individuals genotypes according to the sorted marker order
for(int j=0;j<chromosomes.size();j++){
Chromosome tempChrom = (Chromosome)chromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
for(int j=0;j<extraTrioChromosomes.size();j++) {
Chromosome tempChrom = (Chromosome)extraTrioChromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
//sort pedfile objects
//todo: this should really be done before pedfile is subjected to any processing.
//todo: that would require altering some order of operations in dealing with inputs
//todo: this will fry an out-of-order haps file...grr
Vector unsortedRes = pedFile.getResults();
Vector sortedRes = new Vector();
for (int i = 0; i < realPos.length; i++){
sortedRes.add(unsortedRes.elementAt(realPos[i]));
}
pedFile.setResults(sortedRes);
Vector o = pedFile.getAllIndividuals();
for (int i = 0; i < o.size(); i++){
Individual ind = (Individual) o.get(i);
byte[] sortedMarkersa = new byte[ind.getNumMarkers()];
byte[] sortedMarkersb = new byte[ind.getNumMarkers()];
boolean[] unsortedZeroed = ind.getZeroedArray();
boolean[] sortedZeroed = new boolean[unsortedZeroed.length];
for (int j = 0; j < ind.getNumMarkers(); j++){
sortedMarkersa[j] = ind.getAllele(realPos[j],0);
sortedMarkersb[j] = ind.getAllele(realPos[j],1);
sortedZeroed[j] = unsortedZeroed[realPos[j]];
}
ind.setMarkers(sortedMarkersa, sortedMarkersb);
ind.setZeroedArray(sortedZeroed);
}
}
}catch (HaploViewException e){
throw(e);
}finally{
double numChroms = chromosomes.size();
Vector markerInfo = new Vector();
double[] numBadGenotypes = new double[Chromosome.getUnfilteredSize()];
percentBadGenotypes = new double[Chromosome.getUnfilteredSize()];
Vector results = null;
if (pedFile != null){
results = pedFile.getResults();
}
long prevPosition = Long.MIN_VALUE;
SNP prevMarker = null;
MarkerResult pmr = null;
for (int i = 0; i < Chromosome.getUnfilteredSize(); i++){
MarkerResult mr = null;
if (results != null){
mr = (MarkerResult)results.elementAt(i);
}
//to compute minor/major alleles, browse chrom list and count instances of each allele
byte a1 = 0; byte a2 = 0;
double numa1 = 0; double numa2 = 0;
for (int j = 0; j < chromosomes.size(); j++){
//if there is a data point for this marker on this chromosome
byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getUnfilteredGenotype(i);
if (!(thisAllele == 0)){
if (thisAllele >= 5){
numa1+=0.5; numa2+=0.5;
if (thisAllele < 9){
if (a1==0){
a1 = (byte)(thisAllele-4);
}else if (a2 == 0){
if (!(thisAllele-4 == a1)){
a2 = (byte)(thisAllele-4);
}
}
}
}else if (a1 == 0){
a1 = thisAllele; numa1++;
}else if (thisAllele == a1){
numa1++;
}else{
numa2++;
a2 = thisAllele;
}
}
else {
numBadGenotypes[i]++;
}
}
- if (numa2 > numa1){
+ if (numa2 >= numa1){
byte temp = a1;
double tempnum = numa1;
numa1 = numa2;
a1 = a2;
numa2 = tempnum;
a2 = temp;
}
double maf;
if (mr != null){
maf = Util.roundDouble(mr.getMAF(),3);
}else{
maf = Util.roundDouble((numa2/(numa1+numa2)),3);
}
if (Chromosome.markers == null || !infoProblem){
if (infoKnown){
long pos = Long.parseLong((String)positions.elementAt(i));
SNP thisMarker = (new SNP((String)names.elementAt(i),
pos, maf, a1, a2,
(String)extras.elementAt(i)));
markerInfo.add(thisMarker);
if (mr != null){
double genoPC = mr.getGenoPercent();
//check to make sure adjacent SNPs do not have identical positions
if (prevPosition != Long.MIN_VALUE){
//only do this for markers 2..N, since we're comparing to the previous location
if (pos == prevPosition){
dupsToBeFlagged = true;
if (genoPC >= pmr.getGenoPercent()){
//use this one because it has more genotypes
thisMarker.setDup(1);
prevMarker.setDup(2);
}else{
//use the other one because it has more genotypes
thisMarker.setDup(2);
prevMarker.setDup(1);
}
}
}
prevPosition = pos;
prevMarker = thisMarker;
pmr = mr;
}
}else{
markerInfo.add(new SNP(null,i+1,maf,a1,a2));
}
percentBadGenotypes[i] = numBadGenotypes[i]/numChroms;
}
}
if (Chromosome.markers == null || !infoProblem){
Chromosome.markers = markerInfo;
}
}
}
public Vector prepareHapsInput(String name) throws IOException, HaploViewException, PedFileException {
//this method is called to suck in data from a file (its only argument)
//of genotypes and sets up the Chromosome objects.
Vector chroms = new Vector();
Vector hapsFileStrings = new Vector();
BufferedReader reader;
HaploData.setPhasedData(false);
try{
URL inURL = new URL(name);
reader = new BufferedReader(new InputStreamReader(inURL.openStream()));
}catch(MalformedURLException mfe){
File inFile = new File(name);
if (inFile.length() < 1){
throw new HaploViewException("Genotype file is empty or nonexistent: " + inFile.getName());
}
reader = new BufferedReader(new FileReader(inFile));
}catch(IOException ioe){
throw new HaploViewException("Could not connect to " + name);
}
String line;
while((line = reader.readLine())!=null){
if (line.length() == 0){
//skip blank lines
continue;
}
if (line.startsWith("#")){
//skip comments
continue;
}
hapsFileStrings.add(line);
}
pedFile = new PedFile();
pedFile.parseHapsFile(hapsFileStrings);
Vector result = pedFile.check();
Vector indList = pedFile.getUnrelatedIndividuals();
numSingletons = 0;
Individual currentInd;
int numMarkers = 0;
for (int x=0; x<indList.size(); x++){
currentInd = (Individual)indList.elementAt(x);
numMarkers = currentInd.getNumMarkers();
byte[] chrom1 = new byte[numMarkers];
byte[] chrom2 = new byte[numMarkers];
for (int i = 0; i < numMarkers; i++){
/*byte[] thisMarker;
thisMarker = currentInd.getMarker(i);
chrom1[i] = thisMarker[0];
chrom2[i] = thisMarker[1];
*/
chrom1[i] = currentInd.getAllele(i,0);
chrom2[i] = currentInd.getAllele(i,1);
}
chroms.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),chrom1,currentInd.getAffectedStatus(),0, false));
chroms.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),chrom2,currentInd.getAffectedStatus(),0, false));
numSingletons++;
}
chromosomes = chroms;
//wipe clean any existing marker info so we know we're starting clean with a new file
Chromosome.markers = null;
return result;
}
public Vector linkageToChrom(String name, int type)
throws IllegalArgumentException, HaploViewException, PedFileException, IOException{
Vector pedFileStrings = new Vector();
Vector hapsDataStrings = new Vector();
HaploData.setPhasedData(false);
BufferedReader reader;
try{
URL inURL = new URL(name);
reader = new BufferedReader(new InputStreamReader(inURL.openStream()));
}catch(MalformedURLException mfe){
File inFile = new File(name);
if (inFile.length() < 1){
throw new HaploViewException("Genotype file is empty or nonexistent: " + inFile.getName());
}
reader = new BufferedReader(new FileReader(inFile));
}catch(IOException ioe){
throw new HaploViewException("Could not connect to " + name);
}
String line;
while((line = reader.readLine())!=null){
if (line.length() == 0){
//skip blank lines
continue;
}
if (line.startsWith("#@")){
hapsDataStrings.add(line.substring(2));
continue;
}
if (line.startsWith("#")){
//skip comments
continue;
}
pedFileStrings.add(line);
}
pedFile = new PedFile();
if (type == PED_FILE){
pedFile.parseLinkage(pedFileStrings);
}else{
pedFile.parseHapMap(pedFileStrings, hapsDataStrings);
}
Vector result = pedFile.check();
Vector allInds = pedFile.getAllIndividuals();
Vector unrelatedInds = pedFile.getUnrelatedIndividuals();
HashSet unrelatedHash = new HashSet(unrelatedInds);
HashSet indsInTrio = new HashSet();
int numMarkers = 0;
numSingletons = 0;
numTrios = 0;
numPeds = pedFile.getNumFamilies();
extraTrioChromosomes = new Vector();
Individual currentInd;
Family currentFamily;
Vector chrom = new Vector();
//first time through we deal with trios.
for(int x=0; x < allInds.size(); x++){
currentInd = (Individual)allInds.get(x);
boolean haploid = ((currentInd.getGender() == 1) && Chromosome.getDataChrom().equalsIgnoreCase("chrx"));
currentFamily = pedFile.getFamily(currentInd.getFamilyID());
if (currentFamily.containsMember(currentInd.getMomID()) &&
currentFamily.containsMember(currentInd.getDadID())){
//if indiv has both parents
Individual mom = currentFamily.getMember(currentInd.getMomID());
Individual dad = currentFamily.getMember(currentInd.getDadID());
//if (unrelatedInds.contains(mom) && unrelatedInds.contains(dad)){
numMarkers = currentInd.getNumMarkers();
byte[] dadT = new byte[numMarkers];
byte[] dadU = new byte[numMarkers];
byte[] momT = new byte[numMarkers];
byte[] momU = new byte[numMarkers];
for (int i = 0; i < numMarkers; i++){
byte kid1, kid2;
if (currentInd.getZeroed(i)){
kid1 = 0;
kid2 = 0;
}else{
kid1 = currentInd.getAllele(i,0);
kid2 = currentInd.getAllele(i,1);
}
byte mom1,mom2;
if (currentFamily.getMember(currentInd.getMomID()).getZeroed(i)){
mom1 = 0;
mom2 = 0;
}else{
mom1 = (currentFamily.getMember(currentInd.getMomID())).getAllele(i,0);
mom2 = (currentFamily.getMember(currentInd.getMomID())).getAllele(i,1);
}
byte dad1,dad2;
if (currentFamily.getMember(currentInd.getDadID()).getZeroed(i)){
dad1 = 0;
dad2 = 0;
}else{
dad1 = (currentFamily.getMember(currentInd.getDadID())).getAllele(i,0);
dad2 = (currentFamily.getMember(currentInd.getDadID())).getAllele(i,1);
}
if(haploid) {
if(kid1 == 0) {
//kid missing
dadU[i] = dad1;
if (mom1 == mom2) {
momT[i] = mom1;
momU[i] = mom1;
} else if (mom1 != 0 && mom2 != 0){
momT[i] = (byte)(4+mom1);
momU[i] = (byte)(4+mom2);
}
} else {
dadU[i] = dad1;
if (mom1 == 0) {
momT[i] = kid1;
momU[i] = 0;
} else if (mom1 == kid1) {
momT[i] = mom1;
momU[i] = mom2;
} else {
momT[i] = mom2;
momU[i] = mom1;
}
}
}else {
if (kid1 == 0 || kid2 == 0) {
//kid missing
if (dad1 == dad2) {
dadT[i] = dad1;
dadU[i] = dad1;
} else if (dad1 != 0 && dad2 != 0) {
dadT[i] = (byte)(4+dad1);
dadU[i] = (byte)(4+dad2);
}
if (mom1 == mom2) {
momT[i] = mom1;
momU[i] = mom1;
} else if (mom1 != 0 && mom2 != 0){
momT[i] = (byte)(4+mom1);
momU[i] = (byte)(4+mom2);
}
} else if (kid1 == kid2) {
//kid homozygous
if (dad1 == 0) {
dadT[i] = kid1;
dadU[i] = 0;
} else if (dad1 == kid1) {
dadT[i] = dad1;
dadU[i] = dad2;
} else {
dadT[i] = dad2;
dadU[i] = dad1;
}
if (mom1 == 0) {
momT[i] = kid1;
momU[i] = 0;
} else if (mom1 == kid1) {
momT[i] = mom1;
momU[i] = mom2;
} else {
momT[i] = mom2;
momU[i] = mom1;
}
} else {
//kid heterozygous and this if tree's a bitch
if (dad1 == 0 && mom1 == 0) {
//both missing
dadT[i] = 0;
dadU[i] = 0;
momT[i] = 0;
momU[i] = 0;
} else if (dad1 == 0 && mom1 != mom2) {
//dad missing mom het
dadT[i] = 0;
dadU[i] = 0;
momT[i] = (byte)(4+mom1);
momU[i] = (byte)(4+mom2);
} else if (mom1 == 0 && dad1 != dad2) {
//dad het mom missing
dadT[i] = (byte)(4+dad1);
dadU[i] = (byte)(4+dad2);
momT[i] = 0;
momU[i] = 0;
} else if (dad1 == 0 && mom1 == mom2) {
//dad missing mom hom
momT[i] = mom1;
momU[i] = mom1;
dadU[i] = 0;
if (kid1 == mom1) {
dadT[i] = kid2;
} else {
dadT[i] = kid1;
}
} else if (mom1 == 0 && dad1 == dad2) {
//mom missing dad hom
dadT[i] = dad1;
dadU[i] = dad1;
momU[i] = 0;
if (kid1 == dad1) {
momT[i] = kid2;
} else {
momT[i] = kid1;
}
} else if (dad1 == dad2 && mom1 != mom2) {
//dad hom mom het
dadT[i] = dad1;
dadU[i] = dad2;
if (kid1 == dad1) {
momT[i] = kid2;
momU[i] = kid1;
} else {
momT[i] = kid1;
momU[i] = kid2;
}
} else if (mom1 == mom2 && dad1 != dad2) {
//dad het mom hom
momT[i] = mom1;
momU[i] = mom2;
if (kid1 == mom1) {
dadT[i] = kid2;
dadU[i] = kid1;
} else {
dadT[i] = kid1;
dadU[i] = kid2;
}
} else if (dad1 == dad2 && mom1 == mom2) {
//mom & dad hom
dadT[i] = dad1;
dadU[i] = dad1;
momT[i] = mom1;
momU[i] = mom1;
} else {
//everybody het
dadT[i] = (byte)(4+dad1);
dadU[i] = (byte)(4+dad2);
momT[i] = (byte)(4+mom1);
momU[i] = (byte)(4+mom2);
}
}
}
}
if(unrelatedHash.contains(mom) && unrelatedHash.contains(dad) && unrelatedHash.contains(currentInd)){
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),momT, mom.getAffectedStatus(),currentInd.getAffectedStatus(), false));
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),momU, mom.getAffectedStatus(),currentInd.getAffectedStatus(), false));
if(haploid) {
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadU, dad.getAffectedStatus(),currentInd.getAffectedStatus(), false));
((Chromosome)chrom.lastElement()).setHaploid(true);
}else if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadT, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
((Chromosome)chrom.lastElement()).setHaploid(true);
}else {
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadT, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadU, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
}
numTrios++;
indsInTrio.add(mom);
indsInTrio.add(dad);
indsInTrio.add(currentInd);
//}
}else{
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),momT, mom.getAffectedStatus(),currentInd.getAffectedStatus(), false));
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),momU, mom.getAffectedStatus(),currentInd.getAffectedStatus(), false));
if(haploid) {
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadU, dad.getAffectedStatus(),currentInd.getAffectedStatus(), false));
((Chromosome)extraTrioChromosomes.lastElement()).setHaploid(true);
}else if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadT, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
((Chromosome)extraTrioChromosomes.lastElement()).setHaploid(true);
}else {
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadT, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
extraTrioChromosomes.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),dadU, dad.getAffectedStatus(), currentInd.getAffectedStatus(), false));
}
}
}
}
for (int x=0; x<unrelatedInds.size(); x++){
currentInd = (Individual)unrelatedInds.get(x);
boolean haploid = ((currentInd.getGender() == 1) && Chromosome.getDataChrom().equalsIgnoreCase("chrx"));
if (!indsInTrio.contains(currentInd)){
//ind has no parents or kids -- he's a singleton
numMarkers = currentInd.getNumMarkers();
byte[] chrom1 = new byte[numMarkers];
byte[] chrom2 = new byte[numMarkers];
for (int i = 0; i < numMarkers; i++){
byte thisMarkerA, thisMarkerB;
if (currentInd.getZeroed(i)){
thisMarkerA = 0;
thisMarkerB = 0;
}else{
thisMarkerA = currentInd.getAllele(i,0);
thisMarkerB = currentInd.getAllele(i,1);
}
if (thisMarkerA == thisMarkerB || thisMarkerA == 0 || thisMarkerB == 0){
chrom1[i] = thisMarkerA;
chrom2[i] = thisMarkerB;
}else{
chrom1[i] = (byte)(4+thisMarkerA);
chrom2[i] = (byte)(4+thisMarkerB);
}
}
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),chrom1, currentInd.getAffectedStatus(), -1, false));
if(!haploid){
chrom.add(new Chromosome(currentInd.getFamilyID(),currentInd.getIndividualID(),chrom2,currentInd.getAffectedStatus(), -1, false));
}else{
((Chromosome)chrom.lastElement()).setHaploid(true);
}
numSingletons++;
}
}
chromosomes = chrom;
//wipe clean any existing marker info so we know we're starting with a new file
Chromosome.markers = null;
return result;
}
public Vector phasedToChrom(String[] info, boolean downloadFile)
throws IllegalArgumentException, HaploViewException, PedFileException, IOException{
infoKnown = true;
pedFile = new PedFile();
if (downloadFile){
pedFile.parsePhasedDownload(info);
}else{
pedFile.parsePhasedData(info);
}
HaploData.setPhasedData(true);
Vector result = pedFile.check();
Vector indList = pedFile.getUnrelatedIndividuals();
Vector chroms = new Vector();
Individual currentInd;
int numMarkers;
byte thisMarkerA, thisMarkerB;
numSingletons = 0;
for (int x=0; x < indList.size(); x++){
currentInd = (Individual)indList.get(x);
numMarkers = currentInd.getNumMarkers();
byte[] chrom1 = new byte[numMarkers];
byte[] chrom2 = new byte[numMarkers];
for (int i=0; i < numMarkers; i++){
thisMarkerA = currentInd.getAllele(i,0);
thisMarkerB = currentInd.getAllele(i,1);
chrom1[i] = thisMarkerA;
chrom2[i] = thisMarkerB;
}
if(Chromosome.getDataChrom().equalsIgnoreCase("chrx") && currentInd.getGender() == Individual.MALE){
chroms.add(new Chromosome(currentInd.getFamilyID(), currentInd.getIndividualID(), chrom1, currentInd.getAffectedStatus(), 0, true));
((Chromosome)chroms.lastElement()).setHaploid(true);
}else{
chroms.add(new Chromosome(currentInd.getFamilyID(), currentInd.getIndividualID(), chrom1, currentInd.getAffectedStatus(), 0, true));
chroms.add(new Chromosome(currentInd.getFamilyID(), currentInd.getIndividualID(), chrom2, currentInd.getAffectedStatus(), 0, true));
}
numSingletons++;
}
chromosomes = chroms;
//wipe clean any existing marker info so we know we're starting clean with a new file
Chromosome.markers = null;
return result;
}
void generateDPrimeTable(){
//calculating D prime requires the number of each possible 2 marker
//haplotype in the dataset
dpTable = new DPrimeTable(Chromosome.getUnfilteredSize());
int maxdist = Options.getMaxDistance();
dPrimeTotalCount = ((Chromosome.getUnfilteredSize()-1)*(Chromosome.getUnfilteredSize()-1))/2;
dPrimeCount = 0;
//loop through all marker pairs
for (int pos1 = 0; pos1 < Chromosome.getUnfilteredSize()-1; pos1++){
Vector dpTemp= new Vector();
for (int pos2 = pos1 + 1; pos2 < Chromosome.getUnfilteredSize(); pos2++){
//if the markers are too far apart don't try to compare them
long sep = Chromosome.getUnfilteredMarker(pos2).getPosition() - Chromosome.getUnfilteredMarker(pos1).getPosition();
if (maxdist > 0){
if (sep <= maxdist){
dpTemp.add(computeDPrime(pos1,pos2));
}
}else{
//maxdist==0 is the convention used to force us to compare all the markers
dpTemp.add(computeDPrime(pos1,pos2));
}
dPrimeCount++;
}
dpTable.addMarker(dpTemp,pos1);
}
}
public Haplotype[][] generateBlockHaplotypes(Vector blocks) throws HaploViewException{
Haplotype[][] rawHaplotypes = generateHaplotypes(blocks, true);
Haplotype[][] tempHaplotypes = new Haplotype[rawHaplotypes.length][];
for (int i = 0; i < rawHaplotypes.length; i++) {
Vector orderedHaps = new Vector();
//step through each haplotype in this block
for (int hapCount = 0; hapCount < rawHaplotypes[i].length; hapCount++) {
if (orderedHaps.size() == 0) {
orderedHaps.add(rawHaplotypes[i][hapCount]);
} else {
for (int j = 0; j < orderedHaps.size(); j++) {
if (((Haplotype)(orderedHaps.elementAt(j))).getPercentage() <
rawHaplotypes[i][hapCount].getPercentage()) {
orderedHaps.add(j, rawHaplotypes[i][hapCount]);
break;
}
if ((j+1) == orderedHaps.size()) {
orderedHaps.add(rawHaplotypes[i][hapCount]);
break;
}
}
}
}
tempHaplotypes[i] = new Haplotype[orderedHaps.size()];
orderedHaps.copyInto(tempHaplotypes[i]);
}
tempHaplotypes = generateCrossovers(tempHaplotypes);
haplotypes = tempHaplotypes;
this.rawHaplotypes = rawHaplotypes;
return tempHaplotypes;
}
public Haplotype[][] generateHaplotypes(Vector blocks, boolean storeEM) throws HaploViewException{
Haplotype[][] rawHaplotypes = new Haplotype[blocks.size()][];
for (int k = 0; k < blocks.size(); k++){
int[] preFiltBlock = (int[])blocks.elementAt(k);
int[] theBlock;
int[] selectedMarkers = new int[0];
int[] equivClass = new int[0];
if (preFiltBlock.length > 30){
equivClass = new int[preFiltBlock.length];
int classCounter = 0;
for (int x = 0; x < preFiltBlock.length; x++){
int marker1 = preFiltBlock[x];
//already been lumped into an equivalency class
if (equivClass[x] != 0){
continue;
}
//start a new equivalency class for this SNP
classCounter ++;
equivClass[x] = classCounter;
for (int y = x+1; y < preFiltBlock.length; y++){
int marker2 = preFiltBlock[y];
if (marker1 > marker2){
int tmp = marker1; marker1 = marker2; marker2 = tmp;
}
if ( dpTable.getLDStats(marker1,marker2) != null
&& dpTable.getLDStats(marker1,marker2).getRSquared() == 1.0){
//these two SNPs are redundant
equivClass[y] = classCounter;
}
}
}
//parse equivalency classes
selectedMarkers = new int[classCounter];
for (int x = 0; x < selectedMarkers.length; x++){
selectedMarkers[x] = -1;
}
for (int x = 0; x < classCounter; x++){
double genoPC = 1.0;
for (int y = 0; y < equivClass.length; y++){
if (equivClass[y] == x+1){
if (percentBadGenotypes[Chromosome.realIndex[preFiltBlock[y]]] <= genoPC){
selectedMarkers[x] = preFiltBlock[y];
genoPC = percentBadGenotypes[Chromosome.realIndex[preFiltBlock[y]]];
}
}
}
}
theBlock = selectedMarkers;
}else{
theBlock = preFiltBlock;
}
//kirby patch
EM theEM = new EM(chromosomes,numTrios, extraTrioChromosomes);
theEM.doEM(theBlock);
Haplotype[] tempArray = new Haplotype[theEM.numHaplos()];
int[][] returnedHaplos = theEM.getHaplotypes();
double[] returnedFreqs = theEM.getFrequencies();
for (int i = 0; i < theEM.numHaplos(); i++){
int[] genos = new int[returnedHaplos[i].length];
for (int j = 0; j < genos.length; j++){
if (returnedHaplos[i][j] == 1){
genos[j] = Chromosome.getMarker(theBlock[j]).getMajor();
}else{
if (Chromosome.getMarker(theBlock[j]).getMinor() == 0){
genos[j] = 8;
}else{
genos[j] = Chromosome.getMarker(theBlock[j]).getMinor();
}
}
}
if (selectedMarkers.length > 0){
//we need to reassemble the haplotypes
Hashtable hapsHash = new Hashtable();
//add to hash all the genotypes we phased
for (int q = 0; q < genos.length; q++){
hapsHash.put(new Integer(theBlock[q]), new Integer(genos[q]));
}
//now add all the genotypes we didn't bother phasing, based on
//which marker they are identical to
for (int q = 0; q < equivClass.length; q++){
int currentClass = equivClass[q]-1;
if (selectedMarkers[currentClass] == preFiltBlock[q]){
//we alredy added the phased genotypes above
continue;
}
int indexIntoBlock=0;
for (int x = 0; x < theBlock.length; x++){
if (theBlock[x] == selectedMarkers[currentClass]){
indexIntoBlock = x;
break;
}
}
//this (somewhat laboriously) reconstructs whether to add the minor or major allele
//for markers with MAF close to 0.50 we can't use major/minor alleles to match
//'em up 'cause these might change given missing data
boolean success = false;
if (Chromosome.getMarker(selectedMarkers[currentClass]).getMAF() > 0.4){
for (int z = 0; z < chromosomes.size(); z++){
Chromosome thisChrom = (Chromosome)chromosomes.elementAt(z);
Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++z);
int theGeno = thisChrom.getGenotype(selectedMarkers[currentClass]);
int nextGeno = nextChrom.getGenotype(selectedMarkers[currentClass]);
if (theGeno == nextGeno && theGeno == genos[indexIntoBlock]
&& thisChrom.getGenotype(preFiltBlock[q]) != 0){
hapsHash.put(new Integer(preFiltBlock[q]),
new Integer(thisChrom.getGenotype(preFiltBlock[q])));
success = true;
break;
}
}
}
//either we didn't use careful counting or it didn't work due to missing data
if(!success){
if (Chromosome.getMarker(selectedMarkers[currentClass]).getMajor() ==
genos[indexIntoBlock]){
hapsHash.put(new Integer(preFiltBlock[q]),
new Integer(Chromosome.getMarker(preFiltBlock[q]).getMajor()));
}else{
hapsHash.put(new Integer(preFiltBlock[q]),
new Integer(Chromosome.getMarker(preFiltBlock[q]).getMinor()));
}
}
}
genos = new int[preFiltBlock.length];
for (int q = 0; q < preFiltBlock.length; q++){
genos[q] = ((Integer)hapsHash.get(new Integer(preFiltBlock[q]))).intValue();
}
}
if(storeEM) {
tempArray[i] = new Haplotype(genos, returnedFreqs[i], preFiltBlock, theEM);
}else {
tempArray[i] = new Haplotype(genos, returnedFreqs[i], preFiltBlock, null);
}
//if we are performing association tests, then store the rawHaplotypes
if (Options.getAssocTest() == ASSOC_TRIO){
tempArray[i].setTransCount(theEM.getTransCount(i));
tempArray[i].setUntransCount(theEM.getUntransCount(i));
if(Options.getTdtType() == TDT_PAREN) {
tempArray[i].setDiscordantAlleleCounts(theEM.getDiscordantCounts(i));
}
}else if (Options.getAssocTest() == ASSOC_CC){
tempArray[i].setCaseCount(theEM.getCaseCount(i));
tempArray[i].setControlCount(theEM.getControlCount(i));
}
}
//make the rawHaplotypes array only large enough to hold haps
//which pass threshold above
rawHaplotypes[k] = new Haplotype[theEM.numHaplos()];
for (int z = 0; z < theEM.numHaplos(); z++){
rawHaplotypes[k][z] = tempArray[z];
}
}
return rawHaplotypes;
}
public double[] computeMultiDprime(Haplotype[][] haplos){
double[] multidprimeArray = new double[haplos.length];
for (int gap = 0; gap < haplos.length - 1; gap++){
double[][] multilocusTable = new double[haplos[gap].length][];
double[] rowSum = new double[haplos[gap].length];
double[] colSum = new double[haplos[gap+1].length];
double multilocusTotal = 0;
for (int i = 0; i < haplos[gap].length; i++){
multilocusTable[i] = haplos[gap][i].getCrossovers();
}
//compute multilocus D'
for (int i = 0; i < rowSum.length; i++){
for (int j = 0; j < colSum.length; j++){
rowSum[i] += multilocusTable[i][j];
colSum[j] += multilocusTable[i][j];
multilocusTotal += multilocusTable[i][j];
if (rowSum[i] == 0) rowSum[i] = 0.0001;
if (colSum[j] == 0) colSum[j] = 0.0001;
}
}
double multidprime = 0;
boolean noDivByZero = false;
for (int i = 0; i < rowSum.length; i++){
for (int j = 0; j < colSum.length; j++){
double num = (multilocusTable[i][j]/multilocusTotal) - (rowSum[i]/multilocusTotal)*(colSum[j]/multilocusTotal);
double denom;
if (num < 0){
double denom1 = (rowSum[i]/multilocusTotal)*(colSum[j]/multilocusTotal);
double denom2 = (1.0 - (rowSum[i]/multilocusTotal))*(1.0 - (colSum[j]/multilocusTotal));
if (denom1 < denom2) {
denom = denom1;
}else{
denom = denom2;
}
}else{
double denom1 = (rowSum[i]/multilocusTotal)*(1.0 -(colSum[j]/multilocusTotal));
double denom2 = (1.0 - (rowSum[i]/multilocusTotal))*(colSum[j]/multilocusTotal);
if (denom1 < denom2){
denom = denom1;
}else{
denom = denom2;
}
}
if (denom != 0){
noDivByZero = true;
multidprime += (rowSum[i]/multilocusTotal)*(colSum[j]/multilocusTotal)*Math.abs(num/denom);
}
}
}
if (noDivByZero && multidprime <= 1.00){
multidprimeArray[gap] = multidprime;
}else{
multidprimeArray[gap] = 1.00;
}
}
return multidprimeArray;
}
public void pickTags(Haplotype[][] haplos){
for (int i = 0; i < haplos.length; i++){
//first clear the tags for this block
haplos[i][0].clearTags();
//next pick the tagSNPs
Vector theBestSubset = getBestSubset(haplos[i]);
for (int j = 0; j < theBestSubset.size(); j++){
haplos[i][0].addTag(((Integer)theBestSubset.elementAt(j)).intValue());
}
for (int k = 1; k < haplos[i].length; k++){
//so the tags should be a property of the block, but there's no object to represent it right now
//so we just make sure we copy the tags into all the haps in this block...sorry, I suck.
haplos[i][k].setTags(haplos[i][0].getTags());
}
}
}
public Haplotype[][] orderByCrossing(Haplotype[][] haplos){
//seed first block with ordering numbers
for (int u = 0; u < haplos[0].length; u++){
haplos[0][u].setListOrder(u);
}
for (int gap = 0; gap < haplos.length - 1; gap++){
//sort based on "straight line" crossings
int hilimit;
int lolimit;
if (haplos[gap+1].length > haplos[gap].length) {
hilimit = haplos[gap+1].length;
lolimit = haplos[gap].length;
}else{
hilimit = haplos[gap].length;
lolimit = haplos[gap+1].length;
}
boolean[] unavailable = new boolean[hilimit];
int[] prevBlockLocs = new int[haplos[gap].length];
for (int q = 0; q < prevBlockLocs.length; q++){
prevBlockLocs[haplos[gap][q].getListOrder()] = q;
}
for (int u = 0; u < haplos[gap+1].length; u++){
double currentBestVal = 0;
int currentBestLoc = -1;
for (int v = 0; v < lolimit; v++){
if (!(unavailable[v])){
if (haplos[gap][prevBlockLocs[v]].getCrossover(u) >= currentBestVal) {
currentBestLoc = haplos[gap][prevBlockLocs[v]].getListOrder();
currentBestVal = haplos[gap][prevBlockLocs[v]].getCrossover(u);
}
}
}
//it didn't get lined up with any of the previous block's markers
//put it at the end of the list
if (currentBestLoc == -1){
for (int v = 0; v < unavailable.length; v++){
if (!(unavailable[v])){
currentBestLoc = v;
break;
}
}
}
haplos[gap+1][u].setListOrder(currentBestLoc);
unavailable[currentBestLoc] = true;
}
}
return haplos;
}
Haplotype[][] generateCrossovers(Haplotype[][] haplos) throws HaploViewException{
Vector crossBlock = new Vector();
double CROSSOVER_THRESHOLD = 0.001; //to what percentage do we want to consider crossings?
if (haplos.length == 0) return null;
for (int gap = 0; gap < haplos.length - 1; gap++){ //compute crossovers for each inter-block gap
Vector preGapSubset = getBestSubset(haplos[gap]);
Vector postGapSubset = getBestSubset(haplos[gap+1]);
int[] preMarkerID = haplos[gap][0].getMarkers(); //index haplos to markers in whole dataset
int[] postMarkerID = haplos[gap+1][0].getMarkers();
crossBlock.clear(); //make a "block" of the markers which id the pre- and post- gap haps
for (int i = 0; i < preGapSubset.size(); i++){
crossBlock.add(new Integer(preMarkerID[((Integer)preGapSubset.elementAt(i)).intValue()]));
}
for (int i = 0; i < postGapSubset.size(); i++){
crossBlock.add(new Integer(postMarkerID[((Integer)postGapSubset.elementAt(i)).intValue()]));
}
Vector inputVector = new Vector();
int[] intArray = new int[crossBlock.size()];
for (int i = 0; i < crossBlock.size(); i++){ //input format for hap generating routine
intArray[i] = ((Integer)crossBlock.elementAt(i)).intValue();
}
inputVector.add(intArray);
Haplotype[] crossHaplos = generateHaplotypes(inputVector, true)[0]; //get haplos of gap
for (int i = 0; i < haplos[gap].length; i++){
double[] crossPercentages = new double[haplos[gap+1].length];
StringBuffer firstHapCodeB = new StringBuffer(preGapSubset.size());
for (int j = 0; j < preGapSubset.size(); j++){ //make a string out of uniquely identifying genotypes for this hap
firstHapCodeB.append(haplos[gap][i].getGeno()[((Integer)preGapSubset.elementAt(j)).intValue()]);
}
String firstHapCode = firstHapCodeB.toString();
for (int gapHaplo = 0; gapHaplo < crossHaplos.length; gapHaplo++){ //look at each crossover hap
if (crossHaplos[gapHaplo].getPercentage() > CROSSOVER_THRESHOLD){
StringBuffer gapBeginHapCodeB = new StringBuffer(preGapSubset.size());
for (int j = 0; j < preGapSubset.size(); j++){ //make a string as above
gapBeginHapCodeB.append(crossHaplos[gapHaplo].getGeno()[j]);
}
String gapBeginHapCode = gapBeginHapCodeB.toString();
if (gapBeginHapCode.equals(firstHapCode)){ //if this crossover hap corresponds to this pregap hap
StringBuffer gapEndHapCodeB = new StringBuffer(preGapSubset.size());
for (int j = preGapSubset.size(); j < crossHaplos[gapHaplo].getGeno().length; j++){
gapEndHapCodeB.append(crossHaplos[gapHaplo].getGeno()[j]);
}
String gapEndHapCode = gapEndHapCodeB.toString();
for (int j = 0; j < haplos[gap+1].length; j++){
StringBuffer endHapCodeB = new StringBuffer();
for (int k = 0; k < postGapSubset.size(); k++){
endHapCodeB.append(haplos[gap+1][j].getGeno()[((Integer)postGapSubset.elementAt(k)).intValue()]);
}
String endHapCode = endHapCodeB.toString();
if (gapEndHapCode.equals(endHapCode)){
crossPercentages[j] = crossHaplos[gapHaplo].getPercentage();
}
}
}
}
}
//thought i needed to fix these percentages, but the raw values are just as good.
/* double percentageSum = 0;
double[] fixedCross = new double[crossPercentages.length];
for (int y = 0; y < crossPercentages.length; y++){
percentageSum += crossPercentages[y];
}
for (int y = 0; y < crossPercentages.length; y++){
fixedCross[y] = crossPercentages[y]/percentageSum;
}*/
haplos[gap][i].addCrossovers(crossPercentages);
}
}
return haplos;
}
Vector getBestSubset(Haplotype[] thisBlock){ //from a block of haps, find marker subset which uniquely id's all haps
Vector bestSubset = new Vector();
//first make an array with markers ranked by genotyping success rate
Vector genoSuccessRank = new Vector();
Vector genoNumberRank = new Vector();
int[] myMarkers = thisBlock[0].getMarkers();
genoSuccessRank.add(new Double(percentBadGenotypes[Chromosome.realIndex[myMarkers[0]]]));
genoNumberRank.add(new Integer(0));
for (int i = 1; i < myMarkers.length; i++){
boolean inserted = false;
for (int j = 0; j < genoSuccessRank.size(); j++){
if (percentBadGenotypes[Chromosome.realIndex[myMarkers[i]]] < ((Double)(genoSuccessRank.elementAt(j))).doubleValue()){
genoSuccessRank.insertElementAt(new Double(percentBadGenotypes[Chromosome.realIndex[myMarkers[i]]]), j);
genoNumberRank.insertElementAt(new Integer(i), j);
inserted = true;
break;
}
}
if (!(inserted)) {
genoNumberRank.add(new Integer(i));
genoSuccessRank.add(new Double(percentBadGenotypes[Chromosome.realIndex[myMarkers[i]]]));
}
}
for (int i = 0; i < thisBlock.length-1; i++){
int[] firstHap = thisBlock[i].getGeno();
for (int j = i+1; j < thisBlock.length; j++){
int[] secondHap = thisBlock[j].getGeno();
for (int y = 0; y < firstHap.length; y++){
int x = ((Integer)(genoNumberRank.elementAt(y))).intValue();
if (firstHap[x] != secondHap[x]){
if (!(bestSubset.contains(new Integer(x)))){
bestSubset.add(new Integer(x));
break;
} else {
break;
}
}
}
}
}
return bestSubset;
}
void guessBlocks(int method){
guessBlocks(method, blocks);
}
void guessBlocks(int method, Vector custVec){
Vector returnVec = new Vector();
switch(method){
case BLOX_GABRIEL: returnVec = FindBlocks.doGabriel(dpTable); break;
case BLOX_4GAM: returnVec = FindBlocks.do4Gamete(dpTable); break;
case BLOX_SPINE: returnVec = FindBlocks.doSpine(dpTable); break;
case BLOX_CUSTOM: returnVec = custVec; break;
//todo: bad! doesn't check if vector is out of bounds and stuff or blocks out of order
default: returnVec = new Vector(); break;
}
blocks = returnVec;
blocksChanged = true;
//keep track of which markers are in a block
isInBlock = new boolean[Chromosome.getSize()];
for (int i = 0; i < isInBlock.length; i++){
isInBlock[i] = false;
}
for (int i = 0; i < blocks.size(); i++){
int[] markers = (int[])blocks.elementAt(i);
for (int j = 0; j < markers.length; j++){
isInBlock[markers[j]] = true;
}
}
}
public void removeFromBlock(int markerNum) {
if (blocks != null){
OUTER: for (int i = 0; i < blocks.size(); i ++){
int thisBlock[] = (int[])blocks.elementAt(i);
int newBlock[] = new int[thisBlock.length-1];
int count = 0;
for (int j = 0; j < thisBlock.length; j++){
if(markerNum == thisBlock[j]){
blocksChanged = true;
if (newBlock.length < 1){
blocks.removeElementAt(i);
for (int k = 0; k < thisBlock.length; k++){
this.isInBlock[thisBlock[k]] = false;
}
break OUTER;
}
this.isInBlock[markerNum] = false;
for (int k = 0; k < thisBlock.length; k++){
if (!(k==j)){
newBlock[count] = thisBlock[k];
count++;
}
}
blocks.setElementAt(newBlock, i);
break OUTER;
}
}
}
}
}
public void addMarkerIntoSurroundingBlock(int markerNum) {
if (blocks != null){
OUTER: for (int i = 0; i < blocks.size(); i ++){
int thisBlock[] = (int[])blocks.elementAt(i);
int newBlock[] = new int[thisBlock.length+1];
int count = 0;
if(markerNum > thisBlock[0] && markerNum < thisBlock[thisBlock.length-1]){
blocksChanged = true;
this.isInBlock[markerNum] = true;
for (int j = 0; j < thisBlock.length; j++){
newBlock[count] = thisBlock[j];
count++;
if (thisBlock[j] < markerNum && thisBlock[j+1] > markerNum){
newBlock[count] = markerNum;
count++;
}
}
blocks.setElementAt(newBlock, i);
break OUTER;
}
}
}
}
public void addBlock(int firstMarker, int lastMarker) {
if (firstMarker < 0){
firstMarker = 0;
}
if (lastMarker >= Chromosome.realIndex.length){
lastMarker = Chromosome.realIndex.length-1;
}
if (lastMarker - firstMarker < 0){
//something wonky going on
return;
}
int inArray[] = new int[lastMarker-firstMarker+1];
blocksChanged = true;
if (blocks.size() != 0){
boolean placed = false;
for (int i = 0; i < blocks.size(); i++){
int currentBlock[] = (int[])blocks.elementAt(i);
//trim out any blocks that are overlapped
if ((lastMarker >= currentBlock[0] && firstMarker <= currentBlock[currentBlock.length-1]) ||
firstMarker <= currentBlock[currentBlock.length-1] && firstMarker >= currentBlock[0]){
for (int j = 0; j < currentBlock.length; j++){
isInBlock[currentBlock[j]] = false;
}
blocks.removeElementAt(i);
i--;
}
}
for (int i = 0; i < blocks.size(); i++){
int currentBlock[] = (int[])blocks.elementAt(i);
if (firstMarker <= currentBlock[0] && !placed){
blocks.insertElementAt(inArray,i);
placed = true;
}
}
if (!placed){
blocks.add(inArray);
}
}else{
blocks.add(inArray);
}
for (int i = 0; i < inArray.length; i++){
inArray[i] = firstMarker+i;
this.isInBlock[firstMarker+i] = true;
}
}
//this method computes the dPrime value for the pair of markers pos1,pos2.
//the method assumes that the given pair are not too far apart (ie the distance
//between them is less than maximum distance).
//NOTE: the values of pos1,pos2 should be unfiltered marker numbers.
public PairwiseLinkage computeDPrime(int pos1, int pos2){
int doublehet = 0;
int[][] twoMarkerHaplos = new int[3][3];
for (int i = 0; i < twoMarkerHaplos.length; i++){
for (int j = 0; j < twoMarkerHaplos[i].length; j++){
twoMarkerHaplos[i][j] = 0;
}
}
//check for non-polymorphic markers
if (Chromosome.getUnfilteredMarker(pos1).getMAF() == 0 || Chromosome.getUnfilteredMarker(pos2).getMAF() == 0){
return null;
}
int[] marker1num = new int[5]; int[] marker2num = new int[5];
marker1num[0]=0;
marker1num[Chromosome.getUnfilteredMarker(pos1).getMajor()]=1;
marker1num[Chromosome.getUnfilteredMarker(pos1).getMinor()]=2;
marker2num[0]=0;
marker2num[Chromosome.getUnfilteredMarker(pos2).getMajor()]=1;
marker2num[Chromosome.getUnfilteredMarker(pos2).getMinor()]=2;
byte a1,a2,b1,b2;
//iterate through all chromosomes in dataset
for (int i = 0; i < chromosomes.size(); i++){
//assign alleles for each of a pair of chromosomes at a marker to four variables
if(!((Chromosome)chromosomes.elementAt(i)).isHaploid()){
a1 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos1];
a2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2];
b1 = ((Chromosome) chromosomes.elementAt(++i)).genotypes[pos1];
b2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2];
if (a1 == 0 || a2 == 0 || b1 == 0 || b2 == 0){
//skip missing data
} else if (((a1 >= 5 || b1 >= 5) && (a2 >= 5 || b2 >= 5)) || (a1 >= 5 && !(a2 == b2)) || (a2 >= 5 && !(a1 == b1))){
doublehet++;
//find doublehets and resolved haplotypes
} else if (a1 >= 5 || b1 >= 5){
twoMarkerHaplos[1][marker2num[a2]]++;
twoMarkerHaplos[2][marker2num[a2]]++;
} else if (a2 >= 5 || b2 >= 5){
twoMarkerHaplos[marker1num[a1]][1]++;
twoMarkerHaplos[marker1num[a1]][2]++;
} else {
twoMarkerHaplos[marker1num[a1]][marker2num[a2]]++;
twoMarkerHaplos[marker1num[b1]][marker2num[b2]]++;
}
}else {
//haploid (x chrom)
a1 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos1];
a2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2];
if(a1 != 0 && a2 != 0) {
twoMarkerHaplos[marker1num[a1]][marker2num[a2]]++;
}
}
}
//another monomorphic marker check
int r1, r2, c1, c2;
r1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[1][2];
r2 = twoMarkerHaplos[2][1] + twoMarkerHaplos[2][2];
c1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[2][1];
c2 = twoMarkerHaplos[1][2] + twoMarkerHaplos[2][2];
if ( (r1==0 || r2==0 || c1==0 || c2==0) && doublehet == 0){
return new PairwiseLinkage(1,0,0,0,0,new double[0]);
}
//compute D Prime for this pair of markers.
//return is a tab delimited string of d', lod, r^2, CI(low), CI(high)
int i,count;
//int j,k,itmp;
int low_i = 0;
int high_i = 0;
double loglike, oldloglike;// meand, mean2d, sd;
double tmp;//g,h,m,tmp,r;
double num, denom1, denom2, denom, dprime;//, real_dprime;
double pA1, pB1, pA2, pB2, loglike1, loglike0, rsq;
double tmpAA, tmpAB, tmpBA, tmpBB, dpr;// tmp2AA, tmp2AB, tmp2BA, tmp2BB;
double total_prob, sum_prob;
double lsurface[] = new double[101];
/* store arguments in externals and compute allele frequencies */
known[AA]=twoMarkerHaplos[1][1];
known[AB]=twoMarkerHaplos[1][2];
known[BA]=twoMarkerHaplos[2][1];
known[BB]=twoMarkerHaplos[2][2];
unknownDH=doublehet;
total_chroms= (int)(known[AA]+known[AB]+known[BA]+known[BB]+(2*unknownDH));
pA1 = (known[AA]+known[AB]+unknownDH) / (double) total_chroms;
pB1 = 1.0-pA1;
pA2 = (known[AA]+known[BA]+unknownDH) / (double) total_chroms;
pB2 = 1.0-pA2;
const_prob = 0.1;
/* set initial conditions */
if (const_prob < 0.00) {
probHaps[AA]=pA1*pA2;
probHaps[AB]=pA1*pB2;
probHaps[BA]=pB1*pA2;
probHaps[BB]=pB1*pB2;
} else {
probHaps[AA]=const_prob;
probHaps[AB]=const_prob;
probHaps[BA]=const_prob;
probHaps[BB]=const_prob;;
/* so that the first count step will produce an
initial estimate without inferences (this should
be closer and therefore speedier than assuming
they are all at equal frequency) */
count_haps(0);
estimate_p();
}
/* now we have an initial reasonable guess at p we can
start the EM - let the fun begin */
const_prob=0.0;
count=1; loglike=-999999999.0;
do {
oldloglike=loglike;
count_haps(count);
loglike = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]))/LN10 + ((double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10;
if (Math.abs(loglike-oldloglike) < TOLERANCE) break;
estimate_p();
count++;
} while(count < 1000);
/* in reality I've never seen it need more than 10 or so iterations
to converge so this is really here just to keep it from running off into eternity */
loglike1 = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]) + (double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10;
loglike0 = (known[AA]*Math.log(pA1*pA2) + known[AB]*Math.log(pA1*pB2) + known[BA]*Math.log(pB1*pA2) + known[BB]*Math.log(pB1*pB2) + (double)unknownDH*Math.log(2*pA1*pA2*pB1*pB2))/LN10;
num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA];
if (num < 0) {
/* flip matrix so we get the positive D' */
/* flip AA with AB and BA with BB */
tmp=probHaps[AA]; probHaps[AA]=probHaps[AB]; probHaps[AB]=tmp;
tmp=probHaps[BB]; probHaps[BB]=probHaps[BA]; probHaps[BA]=tmp;
/* flip frequency of second allele */
//done in this slightly asinine way because of a compiler bugz0r in the dec-alpha version of java
//which causes it to try to parallelize the swapping operations and mis-schedules them
pA2 = pA2 + pB2;
pB2 = pA2 - pB2;
pA2 = pA2 - pB2;
//pA2=pB2;pB2=temp;
/* flip counts in the same fashion as p's */
tmp=numHaps[AA]; numHaps[AA]=numHaps[AB]; numHaps[AB]=tmp;
tmp=numHaps[BB]; numHaps[BB]=numHaps[BA]; numHaps[BA]=tmp;
/* num has now undergone a sign change */
num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA];
/* flip known array for likelihood computation */
tmp=known[AA]; known[AA]=known[AB]; known[AB]=tmp;
tmp=known[BB]; known[BB]=known[BA]; known[BA]=tmp;
}
denom1 = (probHaps[AA]+probHaps[BA])*(probHaps[BA]+probHaps[BB]);
denom2 = (probHaps[AA]+probHaps[AB])*(probHaps[AB]+probHaps[BB]);
if (denom1 < denom2) { denom = denom1; }
else { denom = denom2; }
dprime = num/denom;
/* add computation of r^2 = (D^2)/p(1-p)q(1-q) */
rsq = num*num/(pA1*pB1*pA2*pB2);
//real_dprime=dprime;
for (i=0; i<=100; i++) {
dpr = (double)i*0.01;
tmpAA = dpr*denom + pA1*pA2;
tmpAB = pA1-tmpAA;
tmpBA = pA2-tmpAA;
tmpBB = pB1-tmpBA;
if (i==100) {
/* one value will be 0 */
if (tmpAA < 1e-10) tmpAA=1e-10;
if (tmpAB < 1e-10) tmpAB=1e-10;
if (tmpBA < 1e-10) tmpBA=1e-10;
if (tmpBB < 1e-10) tmpBB=1e-10;
}
lsurface[i] = (known[AA]*Math.log(tmpAA) + known[AB]*Math.log(tmpAB) + known[BA]*Math.log(tmpBA) + known[BB]*Math.log(tmpBB) + (double)unknownDH*Math.log(tmpAA*tmpBB + tmpAB*tmpBA))/LN10;
}
/* Confidence bounds #2 - used in Gabriel et al (2002) - translate into posterior dist of D' -
assumes a flat prior dist. of D' - someday we may be able to make
this even more clever by adjusting given the distribution of observed
D' values for any given distance after some large scale studies are complete */
total_prob=sum_prob=0.0;
for (i=0; i<=100; i++) {
lsurface[i] -= loglike1;
lsurface[i] = Math.pow(10.0,lsurface[i]);
total_prob += lsurface[i];
}
for (i=0; i<=100; i++) {
sum_prob += lsurface[i];
if (sum_prob > 0.05*total_prob &&
sum_prob-lsurface[i] < 0.05*total_prob) {
low_i = i-1;
break;
}
}
sum_prob=0.0;
for (i=100; i>=0; i--) {
sum_prob += lsurface[i];
if (sum_prob > 0.05*total_prob &&
sum_prob-lsurface[i] < 0.05*total_prob) {
high_i = i+1;
break;
}
}
if (high_i > 100){ high_i = 100; }
double[] freqarray = {probHaps[AA], probHaps[AB], probHaps[BB], probHaps[BA]};
return new PairwiseLinkage(Util.roundDouble(dprime,3), Util.roundDouble((loglike1-loglike0),2),
Util.roundDouble(rsq,3), ((double)low_i/100.0), ((double)high_i/100.0), freqarray);
}
public void count_haps(int em_round){
/* only the double heterozygote [AB][AB] results in
ambiguous reconstruction, so we'll count the obligates
then tack on the [AB][AB] for clarity */
numHaps[AA] = known[AA];
numHaps[AB] = known[AB];
numHaps[BA] = known[BA];
numHaps[BB] = known[BB];
if (em_round > 0) {
numHaps[AA] += unknownDH* (probHaps[AA]*probHaps[BB])/((probHaps[AA]*probHaps[BB])+(probHaps[AB]*probHaps[BA]));
numHaps[BB] += unknownDH* (probHaps[AA]*probHaps[BB])/((probHaps[AA]*probHaps[BB])+(probHaps[AB]*probHaps[BA]));
numHaps[AB] += unknownDH* (probHaps[AB]*probHaps[BA])/((probHaps[AA]*probHaps[BB])+(probHaps[AB]*probHaps[BA]));
numHaps[BA] += unknownDH* (probHaps[AB]*probHaps[BA])/((probHaps[AA]*probHaps[BB])+(probHaps[AB]*probHaps[BA]));
}
}
public void estimate_p() {
double total= numHaps[AA]+numHaps[AB]+numHaps[BA]+numHaps[BB]+(4.0*const_prob);
probHaps[AA]=(numHaps[AA]+const_prob)/total; if (probHaps[AA] < 1e-10) probHaps[AA]=1e-10;
probHaps[AB]=(numHaps[AB]+const_prob)/total; if (probHaps[AB] < 1e-10) probHaps[AB]=1e-10;
probHaps[BA]=(numHaps[BA]+const_prob)/total; if (probHaps[BA] < 1e-10) probHaps[BA]=1e-10;
probHaps[BB]=(numHaps[BB]+const_prob)/total; if (probHaps[BB] < 1e-10) probHaps[BB]=1e-10;
}
public void saveHapsToText(Haplotype[][] finishedHaplos, double[] multidprime,
File saveHapsFile) throws IOException{
if (finishedHaplos == null) return;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setGroupingUsed(false);
nf.setMinimumFractionDigits(3);
nf.setMaximumFractionDigits(3);
//open file for saving haps text
FileWriter saveHapsWriter = new FileWriter(saveHapsFile);
//go through each block and print haplos
for (int i = 0; i < finishedHaplos.length; i++){
//write block header
int[] markerNums = finishedHaplos[i][0].getMarkers();
saveHapsWriter.write("BLOCK " + (i+1) + ". MARKERS:");
boolean[] tags = finishedHaplos[i][0].getTags();
for (int j = 0; j < markerNums.length; j++){
saveHapsWriter.write(" " + (Chromosome.realIndex[markerNums[j]]+1));
if (Options.isShowBlockTags()){
if (tags[j]) saveHapsWriter.write("!");
}
}
saveHapsWriter.write("\n");
//write haps and crossover percentages
for (int j = 0; j < finishedHaplos[i].length; j++){
if((finishedHaplos[i][j].getPercentage()) >= Options.getHaplotypeDisplayThreshold()) {
int[] theGeno = finishedHaplos[i][j].getGeno();
StringBuffer theHap = new StringBuffer(theGeno.length);
for (int k = 0; k < theGeno.length; k++){
theHap.append(theGeno[k]);
}
saveHapsWriter.write(theHap.toString() + " (" + nf.format(finishedHaplos[i][j].getPercentage()) + ")");
if (i < finishedHaplos.length-1){
saveHapsWriter.write("\t|");
boolean writeTab = false;
for (int crossCount = 0; crossCount < finishedHaplos[i+1].length; crossCount++){
if((finishedHaplos[i+1][crossCount].getPercentage()) >= Options.getHaplotypeDisplayThreshold() ) {
if (crossCount != 0 && writeTab) saveHapsWriter.write("\t");
saveHapsWriter.write(nf.format(finishedHaplos[i][j].getCrossover(crossCount)));
writeTab = true;
}
}
saveHapsWriter.write("|");
}
saveHapsWriter.write("\n");
}
}
if (i < finishedHaplos.length - 1){
saveHapsWriter.write("Multiallelic Dprime: " + nf.format(multidprime[i]) + "\n");
}
}
saveHapsWriter.close();
}
public void saveDprimeToText(File dumpDprimeFile, int source, int start, int stop) throws IOException{
FileWriter saveDprimeWriter = new FileWriter(dumpDprimeFile);
//we use this LinkedList to store the dprime computations for a window of 5 markers
//in either direction in the for loop farther down.
//a tInt value is calculated for each marker which requires the dprime calculations
//for the 5 markers before and 5 after the current marker, so we store these values while we need
//them to avoid unnecesary recomputation.
LinkedList savedDPrimes = new LinkedList();
long dist;
if (infoKnown){
saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\tDist\tT-int\n");
}else{
saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\tT-int\n");
}
boolean adj = false;
if (start == -1 && stop == -1){
//user selected "adjacent markers" option
start = 0; stop = Chromosome.getSize();
adj = true;
}
if (start < 0){
start = 0;
}
if (stop > Chromosome.getSize()){
stop = Chromosome.getSize();
}
PairwiseLinkage currComp = null;
//initialize the savedDPrimes linkedlist with 10 empty arrays of size 10
PairwiseLinkage[] pwlArray = new PairwiseLinkage[10];
savedDPrimes.add(pwlArray);
for(int k=0;k<4;k++) {
savedDPrimes.add(pwlArray.clone());
}
PairwiseLinkage[] tempArray;
if(source != TABLE_TYPE) {
//savedDPrimes is a linkedlist which stores 5 arrays at all times.
//it temporarily stores a set of computeDPrime() results so that we do not
//do them over and over
//each array contains 10 PairwiseLinkage objects.
//each array contains the PairwiseLinkage objects for a marker being compared to the 10 previous markers.
//if marker1 is some marker number, and tempArray is one of the arrays in savedDPrimes, then:
// tempArray[0] = computeDPrime(marker1 - 10, marker1)
// tempArray[9] = computeDPrime(marker1 - 1, marker1)
//if the value of marker1 is less than 10, then the array is filled with nulls up the first valid comparison
//that is, if marker1 = 5, then:
// tempArray[0] through tempArray[4] are null
// tempArray[5] = computeDPrime(marker1-5,marker1)
for(int m=1;m<6;m++) {
tempArray = (PairwiseLinkage[]) savedDPrimes.get(m-1);
for(int n=1;n<11;n++){
if( (start+m) >= Chromosome.getSize() || (start+m-n)<0) {
tempArray[10-n] = null;
}
else {
//the next line used to have Chromosome.getUnfilteredMarker(Chromosome.realIndex[])
//but it seems like this should do the same thing
long sep = Chromosome.getMarker(start+m).getPosition()
- Chromosome.getMarker(start+m-n).getPosition();
if(Options.getMaxDistance() == 0 || sep < Options.getMaxDistance() ) {
tempArray[10-n] = this.computeDPrime(Chromosome.realIndex[start+m-n],Chromosome.realIndex[start+m]);
//tempArray[10-n] = "" + (start+m-n) + "," + (start+m) ;
}
}
}
}
}
for (int i = start; i < stop; i++){
if(source != TABLE_TYPE && i != start) {
//here the first element of savedDPrimes is discarded.
//the array of results for the marker (i+5) is then computed and added to the end of savedDPrimes
tempArray = (PairwiseLinkage[]) savedDPrimes.removeFirst();
for(int m=0;m<10;m++) {
tempArray[m] = null;
}
for(int n=1;n<11;n++){
if(i+5 < Chromosome.getSize() && (i+5-n) >=0) {
long sep = Chromosome.getMarker(i+5).getPosition()
- Chromosome.getMarker(i+5-n).getPosition();
if(Options.getMaxDistance() == 0 || sep < Options.getMaxDistance() ) {
tempArray[10-n] = this.computeDPrime(Chromosome.realIndex[i+5-n],Chromosome.realIndex[i+5]);
}
}
}
savedDPrimes.addLast(tempArray);
}
for (int j = i+1; j < stop; j++){
if (adj){
if (!(i == j-1)){
continue;
}
}
if (source == TABLE_TYPE){
currComp = dpTable.getLDStats(i,j);
}else{
long sep = Chromosome.getMarker(i).getPosition()
- Chromosome.getMarker(j).getPosition();
if(Options.getMaxDistance() == 0 || Math.abs(sep) < Options.getMaxDistance() ) {
currComp = this.computeDPrime(Chromosome.realIndex[i],Chromosome.realIndex[j]);
} else {
currComp = null;
}
}
if(currComp != null) {
double LODSum = 0;
String tInt = "-";
if (i == j-1){
//these are adjacent markers so we'll put in the t-int stat
for (int x = 0; x < 5; x++){
for (int y = 1; y < 6; y++){
if (i-x < 0 || i+y >= Chromosome.getSize()){
continue;
}
tempArray = (PairwiseLinkage[]) savedDPrimes.get(y-1);
PairwiseLinkage tintPair = null;
if (source == TABLE_TYPE){
tintPair = dpTable.getLDStats(i-x,i+y);
}else{
long sep = Chromosome.getUnfilteredMarker(Chromosome.realIndex[i-x]).getPosition()
- Chromosome.getUnfilteredMarker(Chromosome.realIndex[i+y]).getPosition();
if(Options.getMaxDistance() == 0 || Math.abs(sep) < Options.getMaxDistance() ) {
tintPair = tempArray[9-x-y+1];
/*tintPair = this.computeDPrime(Chromosome.realIndex[i-x],
Chromosome.realIndex[i+y]);
if(tempArray[9-x-y+1] == null) {
System.out.println("storage is null ");
}
if(tintPair == null) {
System.out.println("tintPair is null");
}
if(tempArray[9-x-y+1] == tintPair ||
(tintPair != null && tempArray[9-x-y+1] != null && tintPair.getLOD() == tempArray[9-x-y+1].getLOD())) {
System.out.println("match");
}
else {
System.out.println("dont match");
}*/
}
}
if (tintPair != null){
LODSum += tintPair.getLOD();
}
}
}
tInt = String.valueOf(Util.roundDouble(LODSum,2));
}
if (infoKnown){
dist = (Chromosome.getMarker(j)).getPosition() - (Chromosome.getMarker(i)).getPosition();
saveDprimeWriter.write(Chromosome.getMarker(i).getName() +
"\t" + Chromosome.getMarker(j).getName() +
"\t" + currComp.toString() + "\t" + dist + "\t" + tInt +"\n");
}else{
saveDprimeWriter.write((Chromosome.realIndex[i]+1) + "\t" + (Chromosome.realIndex[j]+1) +
"\t" + currComp.toString() + "\t" + tInt + "\n");
}
}
}
}
saveDprimeWriter.close();
}
public void readAnalysisTrack(InputStream inStream) throws HaploViewException, IOException{
//clear out the vector of old values
if (inStream == null){
throw new HaploViewException("Custom analysis track file doesn't exist!");
}
XYSeries xys = new XYSeries(new Integer(analysisTracks.getSeriesCount()));
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String currentLine;
int lineCount = 0;
while ((currentLine = in.readLine()) != null){
lineCount ++;
StringTokenizer st = new StringTokenizer(currentLine);
if (st.countTokens() == 1){
//complain if we have only one col
throw new HaploViewException("File error on line " + lineCount + " in the custom analysis track file");
}else if (st.countTokens() == 0){
//skip blank lines
continue;
}
Double pos, val;
try{
pos = new Double(st.nextToken());
val = new Double(st.nextToken());
}catch (NumberFormatException nfe) {
throw new HaploViewException("Format error on line " + lineCount + " in the custom analysis track file");
}
xys.add(pos,val);
}
analysisTracks.addSeries(xys);
trackExists = true;
}
public Vector readBlocks(InputStream inStream) throws HaploViewException, IOException{
if (inStream == null){
throw new HaploViewException("Blocks file doesn't exist!");
}
Vector cust = new Vector();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String currentLine;
int lineCount = 0;
int highestYet = -1;
while ((currentLine = in.readLine()) != null){
lineCount ++;
StringTokenizer st = new StringTokenizer(currentLine);
if (st.countTokens() == 0){
//skip blank lines
continue;
}
try{
Vector goodies = new Vector();
while (st.hasMoreTokens()){
Integer nextInLine = new Integer(st.nextToken());
for (int y = 0; y < Chromosome.realIndex.length; y++){
//we only keep markers from the input file that are "good" from checkdata
//we also realign the input file to the current "good" subset since input file is
//indexed of all possible markers in the dataset
if (Chromosome.realIndex[y] == nextInLine.intValue() - 1){
goodies.add(new Integer(y));
}
}
}
int thisBlock[] = new int[goodies.size()];
for (int x = 0; x < goodies.size(); x++){
thisBlock[x] = ((Integer)goodies.elementAt(x)).intValue();
if (thisBlock[x] > Chromosome.getUnfilteredSize() || thisBlock[x] < 0){
throw new HaploViewException("Error, marker in block out of bounds: " + thisBlock[x] +
"\non line " + lineCount);
}
if (thisBlock[x] <= highestYet){
throw new HaploViewException("Error, markers/blocks out of order or overlap:\n" +
"on line " + lineCount);
}
highestYet = thisBlock[x];
}
if (thisBlock.length > 0){
cust.add(thisBlock);
}
}catch (NumberFormatException nfe) {
throw new HaploViewException("Format error on line " + lineCount + " in the blocks file");
}
}
return cust;
}
public Haplotype[][] getHaplotypes() {
return haplotypes;
}
public Vector getChromosomes() {
return chromosomes;
}
public Haplotype[][] getRawHaplotypes() {
return rawHaplotypes;
}
public class RSquared {
private double[] rsquareds;
private double[] conditionalProbs;
public RSquared(double[] rsquareds, double[] conditionalProbs) {
this.rsquareds = rsquareds;
this.conditionalProbs = conditionalProbs;
}
public double[] getRsquareds() {
return rsquareds;
}
public double[] getConditionalProbs() {
return conditionalProbs;
}
}
public RSquared getPhasedRSquared(int snp, int[] block){
double rsquareds[] = null;
double conditionalProbs[] = null;
double alleleCounts[][] = null;
int maxIndex =0;
int[] multiMarkerHaplos = null;
boolean monomorphic = false;
if(block.length == 2){
multiMarkerHaplos = new int[8];
int pos1 = snp;
int pos2 = block[0];
int pos3 = block[1];
int[] marker1num = new int[5]; int[] marker2num = new int[5]; int[] marker3num = new int[5];
marker1num[Chromosome.getMarker(pos1).getMajor()]=0;
marker1num[Chromosome.getMarker(pos1).getMinor()]=4;
marker2num[Chromosome.getMarker(pos2).getMajor()]=0;
marker2num[Chromosome.getMarker(pos2).getMinor()]=2;
marker3num[Chromosome.getMarker(pos3).getMajor()]=0;
marker3num[Chromosome.getMarker(pos3).getMinor()]=1;
alleleCounts = new double[3][5];
byte a1,a2,a3,b1,b2,b3;
//iterate through all chromosomes in dataset
for (int i = 0; i < chromosomes.size(); i++){
if(!((Chromosome)chromosomes.elementAt(i)).isHaploid()){
a1 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos1);
a2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
a3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
b1 = ((Chromosome) chromosomes.elementAt(++i)).getGenotype(pos1);
b2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
b3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
multiMarkerHaplos[marker1num[a1] + marker2num[a2] + marker3num[a3]]++;
multiMarkerHaplos[marker1num[b1] + marker2num[b2] + marker3num[b3]]++;
alleleCounts[0][a1]++;
alleleCounts[0][b1]++;
alleleCounts[1][a2]++;
alleleCounts[1][b2]++;
alleleCounts[2][a3]++;
alleleCounts[2][b3]++;
}else {
//haploid
a1 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos1);
a2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
a3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
multiMarkerHaplos[marker1num[a1] + marker2num[a2] + marker3num[a3]]++;
}
}
//check for any monomorphic SNPs
if(alleleCounts[0][Chromosome.getMarker(pos1).getMajor()] == 0 || alleleCounts[0][Chromosome.getMarker(pos1).getMinor()] == 0
|| alleleCounts[1][Chromosome.getMarker(pos2).getMajor()] == 0 || alleleCounts[1][Chromosome.getMarker(pos2).getMinor()] == 0
|| alleleCounts[2][Chromosome.getMarker(pos3).getMajor()] == 0 || alleleCounts[2][Chromosome.getMarker(pos3).getMinor()] == 0){
monomorphic = true;
}
maxIndex = 4;
}else if (block.length == 3){
multiMarkerHaplos = new int[16];
int pos1 = snp;
int pos2 = block[0];
int pos3 = block[1];
int pos4 = block[2];
int[] marker1num = new int[5];
int[] marker2num = new int[5];
int[] marker3num = new int[5];
int[] marker4num = new int[5];
marker1num[Chromosome.getMarker(pos1).getMinor()]=8;
marker2num[Chromosome.getMarker(pos2).getMinor()]=4;
marker3num[Chromosome.getMarker(pos3).getMinor()]=2;
marker4num[Chromosome.getMarker(pos4).getMinor()]=1;
alleleCounts = new double[4][5];
byte a1,a2,a3,a4,b1,b2,b3,b4;
//iterate through all chromosomes in dataset
for (int i = 0; i < chromosomes.size(); i++){
if(!((Chromosome)chromosomes.elementAt(i)).isHaploid()){
a1 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos1);
a2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
a3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
a4 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos4);
b1 = ((Chromosome) chromosomes.elementAt(++i)).getGenotype(pos1);
b2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
b3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
b4 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos4);
multiMarkerHaplos[marker1num[a1] + marker2num[a2] + marker3num[a3] + marker4num[a4]]++;
multiMarkerHaplos[marker1num[b1] + marker2num[b2] + marker3num[b3] + marker4num[b4]]++;
alleleCounts[0][a1]++;
alleleCounts[0][b1]++;
alleleCounts[1][a2]++;
alleleCounts[1][b2]++;
alleleCounts[2][a3]++;
alleleCounts[2][b3]++;
alleleCounts[3][a4]++;
alleleCounts[3][b4]++;
}else {
//haploid
a1 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos1);
a2 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos2);
a3 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos3);
a4 = ((Chromosome) chromosomes.elementAt(i)).getGenotype(pos4);
multiMarkerHaplos[marker1num[a1] + marker2num[a2] + marker3num[a3] + marker4num[a4]]++;
}
}
if(alleleCounts[0][Chromosome.getMarker(pos1).getMajor()] == 0 || alleleCounts[0][Chromosome.getMarker(pos1).getMinor()] == 0
|| alleleCounts[1][Chromosome.getMarker(pos2).getMajor()] == 0 || alleleCounts[1][Chromosome.getMarker(pos2).getMinor()] == 0
|| alleleCounts[2][Chromosome.getMarker(pos3).getMajor()] == 0 || alleleCounts[2][Chromosome.getMarker(pos3).getMinor()] == 0
|| alleleCounts[3][Chromosome.getMarker(pos4).getMajor()] == 0 || alleleCounts[3][Chromosome.getMarker(pos4).getMinor()] == 0){
monomorphic = true;
}
maxIndex =8;
}
//the rest of the code is the same for 2 and 3 marker blocks
rsquareds = new double[maxIndex];
conditionalProbs = new double[maxIndex];
if(monomorphic){
Arrays.fill(rsquareds,0);
Arrays.fill(conditionalProbs,0);
return new RSquared(rsquareds,conditionalProbs);
}
int totalChroms=0;
for(int i = 0;i < multiMarkerHaplos.length;i++){
totalChroms += multiMarkerHaplos[i];
}
double[] freqs = new double[multiMarkerHaplos.length];
for(int i=0;i<freqs.length;i++){
freqs[i] = multiMarkerHaplos[i]/(double)totalChroms;
}
double p=0;
for(int i=0;i< maxIndex; i++){
p += freqs[i];
}
for(int i =0;i< maxIndex;i++){
//calculate r^2
double aa = freqs[i];
double ab = p - freqs[i];
double ba = freqs[i+maxIndex];
double bb = (1-p) - freqs[i+maxIndex];
double q = ba + aa;
double c = aa*bb - ab*ba;
rsquareds[i] = Util.roundDouble((c*c)/(p*(1-p)*q*(1-q)),3);
//calculate conditional prob (ie P(snp | hap))
conditionalProbs[i] = freqs[i]/(freqs[i] + freqs[i+maxIndex]);
}
return new RSquared(rsquareds,conditionalProbs);
}
public static boolean isPhasedData() {
return phasedData;
}
public static void setPhasedData(boolean phasedData) {
HaploData.phasedData = phasedData;
}
}
| true | true | void prepareMarkerInput(InputStream inStream, String[][] hapmapGoodies) throws IOException, HaploViewException{
//this method is called to gather data about the markers used.
//It is assumed that the input file is two columns, the first being
//the name and the second the absolute position. the maxdist is
//used to determine beyond what distance comparisons will not be
//made. if the infile param is null, loads up "dummy info" for
//situation where no info file exists
//An optional third column is supported which is designed to hold
//association study data. If there is a third column there will be
//a visual indicator in the D' display that there is additional data
//and the detailed data can be viewed with a mouse press.
Vector names = new Vector();
HashSet nameSearch = new HashSet();
HashSet dupCheck = new HashSet();
Vector positions = new Vector();
Vector extras = new Vector();
boolean infoProblem = false;
dupsToBeFlagged = false;
dupNames = false;
try{
if (inStream != null){
//read the input file:
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String currentLine;
long prevloc = -1000000000;
int lineCount = 0;
while ((currentLine = in.readLine()) != null){
StringTokenizer st = new StringTokenizer(currentLine);
if (st.countTokens() > 1){
lineCount++;
}else if (st.countTokens() == 1){
//complain if only one field found
throw new HaploViewException("Info file format error on line "+lineCount+
":\n Info file must be of format: <markername> <markerposition>");
}else{
//skip blank lines
continue;
}
String name = st.nextToken();
String l = st.nextToken();
String extra = null;
if (st.hasMoreTokens()) extra = st.nextToken();
long loc;
try{
loc = Long.parseLong(l);
}catch (NumberFormatException nfe){
infoProblem = true;
throw new HaploViewException("Info file format error on line "+lineCount+
":\n\"" + l + "\" should be of type long." +
"\n Info file must be of format: <markername> <markerposition>");
}
//basically if anyone is crazy enough to load a dataset, then go back and load
//an out-of-order info file we tell them to bugger off and start over.
if (loc < prevloc && Chromosome.markers != null){
infoProblem = true;
throw new HaploViewException("Info file out of order with preloaded dataset:\n"+
name + "\nPlease reload data file and info file together.");
}
prevloc = loc;
if (nameSearch.contains(name)){
dupCheck.add(name);
}
names.add(name);
nameSearch.add(name);
positions.add(l);
extras.add(extra);
}
if (lineCount > Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file compared to data file."));
}
if (lineCount < Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file compared to data file."));
}
infoKnown=true;
}
if (hapmapGoodies != null){
//we know some stuff from the hapmap so we'll add it here
for (int x=0; x < hapmapGoodies.length; x++){
if (nameSearch.contains(hapmapGoodies[x][0])){
dupCheck.add(hapmapGoodies[x][0]);
}
names.add(hapmapGoodies[x][0]);
nameSearch.add(hapmapGoodies[x][0]);
positions.add(hapmapGoodies[x][1]);
extras.add(null);
}
infoKnown = true;
}
if(dupCheck.size() > 0) {
int nameCount = names.size();
Hashtable dupCounts = new Hashtable();
for(int i=0;i<nameCount;i++) {
if(dupCheck.contains(names.get(i))){
String n = (String) names.get(i);
if(dupCounts.containsKey(n)){
int numDups = ((Integer) dupCounts.get(n)).intValue();
String newName = n + "." + numDups;
while (nameSearch.contains(newName)){
numDups++;
newName = n + "." + numDups;
}
names.setElementAt(newName,i);
nameSearch.add(newName);
dupCounts.put(n,new Integer(numDups)) ;
}else {
//we leave the first instance with its original name
dupCounts.put(n,new Integer(1));
}
dupNames = true;
}
}
}
//sort the markers
int numLines = names.size();
class SortingHelper implements Comparable{
long pos;
int orderInFile;
public SortingHelper(long pos, int order){
this.pos = pos;
this.orderInFile = order;
}
public int compareTo(Object o) {
SortingHelper sh = (SortingHelper)o;
if (sh.pos > pos){
return -1;
}else if (sh.pos < pos){
return 1;
}else{
return 0;
}
}
}
boolean needSort = false;
Vector sortHelpers = new Vector();
for (int k = 0; k < (numLines); k++){
sortHelpers.add(new SortingHelper(Long.parseLong((String)positions.get(k)),k));
}
//loop through and check if any markers are out of order
for (int k = 1; k < (numLines); k++){
if(((SortingHelper)sortHelpers.get(k)).compareTo(sortHelpers.get(k-1)) < 0) {
needSort = true;
break;
}
}
//if any were out of order, then we need to put them in order
if(needSort){
//throw new HaploViewException("unsorted files not supported at present");
//sort the positions
Collections.sort(sortHelpers);
Vector newNames = new Vector();
Vector newExtras = new Vector();
Vector newPositions = new Vector();
int[] realPos = new int[numLines];
//reorder the vectors names and extras so that they have the same order as the sorted markers
for (int i = 0; i < sortHelpers.size(); i++){
realPos[i] = ((SortingHelper)sortHelpers.get(i)).orderInFile;
newNames.add(names.get(realPos[i]));
newPositions.add(positions.get(realPos[i]));
newExtras.add(extras.get(realPos[i]));
}
names = newNames;
extras = newExtras;
positions = newPositions;
byte[] tempGenotype = new byte[sortHelpers.size()];
//now we reorder all the individuals genotypes according to the sorted marker order
for(int j=0;j<chromosomes.size();j++){
Chromosome tempChrom = (Chromosome)chromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
for(int j=0;j<extraTrioChromosomes.size();j++) {
Chromosome tempChrom = (Chromosome)extraTrioChromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
//sort pedfile objects
//todo: this should really be done before pedfile is subjected to any processing.
//todo: that would require altering some order of operations in dealing with inputs
//todo: this will fry an out-of-order haps file...grr
Vector unsortedRes = pedFile.getResults();
Vector sortedRes = new Vector();
for (int i = 0; i < realPos.length; i++){
sortedRes.add(unsortedRes.elementAt(realPos[i]));
}
pedFile.setResults(sortedRes);
Vector o = pedFile.getAllIndividuals();
for (int i = 0; i < o.size(); i++){
Individual ind = (Individual) o.get(i);
byte[] sortedMarkersa = new byte[ind.getNumMarkers()];
byte[] sortedMarkersb = new byte[ind.getNumMarkers()];
boolean[] unsortedZeroed = ind.getZeroedArray();
boolean[] sortedZeroed = new boolean[unsortedZeroed.length];
for (int j = 0; j < ind.getNumMarkers(); j++){
sortedMarkersa[j] = ind.getAllele(realPos[j],0);
sortedMarkersb[j] = ind.getAllele(realPos[j],1);
sortedZeroed[j] = unsortedZeroed[realPos[j]];
}
ind.setMarkers(sortedMarkersa, sortedMarkersb);
ind.setZeroedArray(sortedZeroed);
}
}
}catch (HaploViewException e){
throw(e);
}finally{
double numChroms = chromosomes.size();
Vector markerInfo = new Vector();
double[] numBadGenotypes = new double[Chromosome.getUnfilteredSize()];
percentBadGenotypes = new double[Chromosome.getUnfilteredSize()];
Vector results = null;
if (pedFile != null){
results = pedFile.getResults();
}
long prevPosition = Long.MIN_VALUE;
SNP prevMarker = null;
MarkerResult pmr = null;
for (int i = 0; i < Chromosome.getUnfilteredSize(); i++){
MarkerResult mr = null;
if (results != null){
mr = (MarkerResult)results.elementAt(i);
}
//to compute minor/major alleles, browse chrom list and count instances of each allele
byte a1 = 0; byte a2 = 0;
double numa1 = 0; double numa2 = 0;
for (int j = 0; j < chromosomes.size(); j++){
//if there is a data point for this marker on this chromosome
byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getUnfilteredGenotype(i);
if (!(thisAllele == 0)){
if (thisAllele >= 5){
numa1+=0.5; numa2+=0.5;
if (thisAllele < 9){
if (a1==0){
a1 = (byte)(thisAllele-4);
}else if (a2 == 0){
if (!(thisAllele-4 == a1)){
a2 = (byte)(thisAllele-4);
}
}
}
}else if (a1 == 0){
a1 = thisAllele; numa1++;
}else if (thisAllele == a1){
numa1++;
}else{
numa2++;
a2 = thisAllele;
}
}
else {
numBadGenotypes[i]++;
}
}
if (numa2 > numa1){
byte temp = a1;
double tempnum = numa1;
numa1 = numa2;
a1 = a2;
numa2 = tempnum;
a2 = temp;
}
double maf;
if (mr != null){
maf = Util.roundDouble(mr.getMAF(),3);
}else{
maf = Util.roundDouble((numa2/(numa1+numa2)),3);
}
if (Chromosome.markers == null || !infoProblem){
if (infoKnown){
long pos = Long.parseLong((String)positions.elementAt(i));
SNP thisMarker = (new SNP((String)names.elementAt(i),
pos, maf, a1, a2,
(String)extras.elementAt(i)));
markerInfo.add(thisMarker);
if (mr != null){
double genoPC = mr.getGenoPercent();
//check to make sure adjacent SNPs do not have identical positions
if (prevPosition != Long.MIN_VALUE){
//only do this for markers 2..N, since we're comparing to the previous location
if (pos == prevPosition){
dupsToBeFlagged = true;
if (genoPC >= pmr.getGenoPercent()){
//use this one because it has more genotypes
thisMarker.setDup(1);
prevMarker.setDup(2);
}else{
//use the other one because it has more genotypes
thisMarker.setDup(2);
prevMarker.setDup(1);
}
}
}
prevPosition = pos;
prevMarker = thisMarker;
pmr = mr;
}
}else{
markerInfo.add(new SNP(null,i+1,maf,a1,a2));
}
percentBadGenotypes[i] = numBadGenotypes[i]/numChroms;
}
}
if (Chromosome.markers == null || !infoProblem){
Chromosome.markers = markerInfo;
}
}
}
| void prepareMarkerInput(InputStream inStream, String[][] hapmapGoodies) throws IOException, HaploViewException{
//this method is called to gather data about the markers used.
//It is assumed that the input file is two columns, the first being
//the name and the second the absolute position. the maxdist is
//used to determine beyond what distance comparisons will not be
//made. if the infile param is null, loads up "dummy info" for
//situation where no info file exists
//An optional third column is supported which is designed to hold
//association study data. If there is a third column there will be
//a visual indicator in the D' display that there is additional data
//and the detailed data can be viewed with a mouse press.
Vector names = new Vector();
HashSet nameSearch = new HashSet();
HashSet dupCheck = new HashSet();
Vector positions = new Vector();
Vector extras = new Vector();
boolean infoProblem = false;
dupsToBeFlagged = false;
dupNames = false;
try{
if (inStream != null){
//read the input file:
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String currentLine;
long prevloc = -1000000000;
int lineCount = 0;
while ((currentLine = in.readLine()) != null){
StringTokenizer st = new StringTokenizer(currentLine);
if (st.countTokens() > 1){
lineCount++;
}else if (st.countTokens() == 1){
//complain if only one field found
throw new HaploViewException("Info file format error on line "+lineCount+
":\n Info file must be of format: <markername> <markerposition>");
}else{
//skip blank lines
continue;
}
String name = st.nextToken();
String l = st.nextToken();
String extra = null;
if (st.hasMoreTokens()) extra = st.nextToken();
long loc;
try{
loc = Long.parseLong(l);
}catch (NumberFormatException nfe){
infoProblem = true;
throw new HaploViewException("Info file format error on line "+lineCount+
":\n\"" + l + "\" should be of type long." +
"\n Info file must be of format: <markername> <markerposition>");
}
//basically if anyone is crazy enough to load a dataset, then go back and load
//an out-of-order info file we tell them to bugger off and start over.
if (loc < prevloc && Chromosome.markers != null){
infoProblem = true;
throw new HaploViewException("Info file out of order with preloaded dataset:\n"+
name + "\nPlease reload data file and info file together.");
}
prevloc = loc;
if (nameSearch.contains(name)){
dupCheck.add(name);
}
names.add(name);
nameSearch.add(name);
positions.add(l);
extras.add(extra);
}
if (lineCount > Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file compared to data file."));
}
if (lineCount < Chromosome.getUnfilteredSize()){
infoProblem = true;
throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file compared to data file."));
}
infoKnown=true;
}
if (hapmapGoodies != null){
//we know some stuff from the hapmap so we'll add it here
for (int x=0; x < hapmapGoodies.length; x++){
if (nameSearch.contains(hapmapGoodies[x][0])){
dupCheck.add(hapmapGoodies[x][0]);
}
names.add(hapmapGoodies[x][0]);
nameSearch.add(hapmapGoodies[x][0]);
positions.add(hapmapGoodies[x][1]);
extras.add(null);
}
infoKnown = true;
}
if(dupCheck.size() > 0) {
int nameCount = names.size();
Hashtable dupCounts = new Hashtable();
for(int i=0;i<nameCount;i++) {
if(dupCheck.contains(names.get(i))){
String n = (String) names.get(i);
if(dupCounts.containsKey(n)){
int numDups = ((Integer) dupCounts.get(n)).intValue();
String newName = n + "." + numDups;
while (nameSearch.contains(newName)){
numDups++;
newName = n + "." + numDups;
}
names.setElementAt(newName,i);
nameSearch.add(newName);
dupCounts.put(n,new Integer(numDups)) ;
}else {
//we leave the first instance with its original name
dupCounts.put(n,new Integer(1));
}
dupNames = true;
}
}
}
//sort the markers
int numLines = names.size();
class SortingHelper implements Comparable{
long pos;
int orderInFile;
public SortingHelper(long pos, int order){
this.pos = pos;
this.orderInFile = order;
}
public int compareTo(Object o) {
SortingHelper sh = (SortingHelper)o;
if (sh.pos > pos){
return -1;
}else if (sh.pos < pos){
return 1;
}else{
return 0;
}
}
}
boolean needSort = false;
Vector sortHelpers = new Vector();
for (int k = 0; k < (numLines); k++){
sortHelpers.add(new SortingHelper(Long.parseLong((String)positions.get(k)),k));
}
//loop through and check if any markers are out of order
for (int k = 1; k < (numLines); k++){
if(((SortingHelper)sortHelpers.get(k)).compareTo(sortHelpers.get(k-1)) < 0) {
needSort = true;
break;
}
}
//if any were out of order, then we need to put them in order
if(needSort){
//throw new HaploViewException("unsorted files not supported at present");
//sort the positions
Collections.sort(sortHelpers);
Vector newNames = new Vector();
Vector newExtras = new Vector();
Vector newPositions = new Vector();
int[] realPos = new int[numLines];
//reorder the vectors names and extras so that they have the same order as the sorted markers
for (int i = 0; i < sortHelpers.size(); i++){
realPos[i] = ((SortingHelper)sortHelpers.get(i)).orderInFile;
newNames.add(names.get(realPos[i]));
newPositions.add(positions.get(realPos[i]));
newExtras.add(extras.get(realPos[i]));
}
names = newNames;
extras = newExtras;
positions = newPositions;
byte[] tempGenotype = new byte[sortHelpers.size()];
//now we reorder all the individuals genotypes according to the sorted marker order
for(int j=0;j<chromosomes.size();j++){
Chromosome tempChrom = (Chromosome)chromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
for(int j=0;j<extraTrioChromosomes.size();j++) {
Chromosome tempChrom = (Chromosome)extraTrioChromosomes.elementAt(j);
for(int i =0;i<sortHelpers.size();i++){
tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]);
}
for(int i=0;i<sortHelpers.size();i++){
tempChrom.setGenotype(tempGenotype[i],i);
}
}
//sort pedfile objects
//todo: this should really be done before pedfile is subjected to any processing.
//todo: that would require altering some order of operations in dealing with inputs
//todo: this will fry an out-of-order haps file...grr
Vector unsortedRes = pedFile.getResults();
Vector sortedRes = new Vector();
for (int i = 0; i < realPos.length; i++){
sortedRes.add(unsortedRes.elementAt(realPos[i]));
}
pedFile.setResults(sortedRes);
Vector o = pedFile.getAllIndividuals();
for (int i = 0; i < o.size(); i++){
Individual ind = (Individual) o.get(i);
byte[] sortedMarkersa = new byte[ind.getNumMarkers()];
byte[] sortedMarkersb = new byte[ind.getNumMarkers()];
boolean[] unsortedZeroed = ind.getZeroedArray();
boolean[] sortedZeroed = new boolean[unsortedZeroed.length];
for (int j = 0; j < ind.getNumMarkers(); j++){
sortedMarkersa[j] = ind.getAllele(realPos[j],0);
sortedMarkersb[j] = ind.getAllele(realPos[j],1);
sortedZeroed[j] = unsortedZeroed[realPos[j]];
}
ind.setMarkers(sortedMarkersa, sortedMarkersb);
ind.setZeroedArray(sortedZeroed);
}
}
}catch (HaploViewException e){
throw(e);
}finally{
double numChroms = chromosomes.size();
Vector markerInfo = new Vector();
double[] numBadGenotypes = new double[Chromosome.getUnfilteredSize()];
percentBadGenotypes = new double[Chromosome.getUnfilteredSize()];
Vector results = null;
if (pedFile != null){
results = pedFile.getResults();
}
long prevPosition = Long.MIN_VALUE;
SNP prevMarker = null;
MarkerResult pmr = null;
for (int i = 0; i < Chromosome.getUnfilteredSize(); i++){
MarkerResult mr = null;
if (results != null){
mr = (MarkerResult)results.elementAt(i);
}
//to compute minor/major alleles, browse chrom list and count instances of each allele
byte a1 = 0; byte a2 = 0;
double numa1 = 0; double numa2 = 0;
for (int j = 0; j < chromosomes.size(); j++){
//if there is a data point for this marker on this chromosome
byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getUnfilteredGenotype(i);
if (!(thisAllele == 0)){
if (thisAllele >= 5){
numa1+=0.5; numa2+=0.5;
if (thisAllele < 9){
if (a1==0){
a1 = (byte)(thisAllele-4);
}else if (a2 == 0){
if (!(thisAllele-4 == a1)){
a2 = (byte)(thisAllele-4);
}
}
}
}else if (a1 == 0){
a1 = thisAllele; numa1++;
}else if (thisAllele == a1){
numa1++;
}else{
numa2++;
a2 = thisAllele;
}
}
else {
numBadGenotypes[i]++;
}
}
if (numa2 >= numa1){
byte temp = a1;
double tempnum = numa1;
numa1 = numa2;
a1 = a2;
numa2 = tempnum;
a2 = temp;
}
double maf;
if (mr != null){
maf = Util.roundDouble(mr.getMAF(),3);
}else{
maf = Util.roundDouble((numa2/(numa1+numa2)),3);
}
if (Chromosome.markers == null || !infoProblem){
if (infoKnown){
long pos = Long.parseLong((String)positions.elementAt(i));
SNP thisMarker = (new SNP((String)names.elementAt(i),
pos, maf, a1, a2,
(String)extras.elementAt(i)));
markerInfo.add(thisMarker);
if (mr != null){
double genoPC = mr.getGenoPercent();
//check to make sure adjacent SNPs do not have identical positions
if (prevPosition != Long.MIN_VALUE){
//only do this for markers 2..N, since we're comparing to the previous location
if (pos == prevPosition){
dupsToBeFlagged = true;
if (genoPC >= pmr.getGenoPercent()){
//use this one because it has more genotypes
thisMarker.setDup(1);
prevMarker.setDup(2);
}else{
//use the other one because it has more genotypes
thisMarker.setDup(2);
prevMarker.setDup(1);
}
}
}
prevPosition = pos;
prevMarker = thisMarker;
pmr = mr;
}
}else{
markerInfo.add(new SNP(null,i+1,maf,a1,a2));
}
percentBadGenotypes[i] = numBadGenotypes[i]/numChroms;
}
}
if (Chromosome.markers == null || !infoProblem){
Chromosome.markers = markerInfo;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.